I am getting the same Error on running rspec that is :-
"Undefined Method - authorize_manage_partner_links"
I am using CANCAN gem in my Gemfile for authorization purposes and i am using Rails version 3.2 and Ruby version 1.9.2.
Please suggest what to do as i am totally new to rspec and rails. I am using a testing database, on importing the database for the first time, when i am running rspec it is showing successful but after that it is showing this error on running the same rspec file. I am using FactoryGirl. and i have defined everything in my factoryrb file as well.
This is my controller--
require 'will_paginate/array'
class PartnerLinksController < ApplicationController
#load_and_authorize_resource
before_filter :authorize_manage_partner_links!
layout "backoffice"
def index
#partner_links = PartnerLink.all
if params[:sortby]
#partner_links = #partner_links.sort_by {|p| p.name} if params[:sortby] == "up"
#partner_links = #partner_links.sort_by {|p| p.name}.reverse if params[:sortby] == "down"
else
#partner_links = #partner_links.sort_by {|p| p.name}
end
total = #partner_links.size
#partner_links = #partner_links.paginate(:page => params[:page], :per_page => 20)
page = params[:page]
if !page
page = 1
end
render :locals => {:total => total, :page => page, :sortby => params[:sortby], :partner_link => #partner_link}
end
def new
#partner_link = PartnerLink.new
end
def edit
#partner_link = PartnerLink.find(params[:id])
end
def create
#partner_link = PartnerLink.new(params[:partner_link])
if #partner_link.save
redirect_to partner_links_url
else
render "new"
end
end
def update
#partner_link = PartnerLink.find(params[:id])
if #partner_link.update_attributes(params[:partner_link])
redirect_to partner_links_url
else
render "edit"
end
end
def destroy
#partner_link = PartnerLink.find(params[:id])
#partner_link.destroy
redirect_to partner_links_url
end
end
This is my rspec controller that i am using--
require 'spec_helper'
describe PartnerLinksController do
before do
FactoryGirl.create(:partner_link)
role_permission
admin_role
user
currency
category
merchant
cart
deal
sign_in user
end
let(:role_permission) {FactoryGirl.create(:role_permission)}
let(:currency) {FactoryGirl.create(:currency)}
let(:merchant) {FactoryGirl.create(:merchant)}
let(:cart) {FactoryGirl.create(:cart)}
let(:deal) {FactoryGirl.create(:deal)}
let(:category) {FactoryGirl.create(:category)}
let(:authentication) {FactoryGirl.create(:authentication)}
let(:user) {FactoryGirl.create(:user)}
let(:admin_role) {FactoryGirl.create(:admin_role)}
describe "index" do
it "Should display all the partner links" do
get :index
end
end
describe "new" do
it "Should create all the partner links" do
get :new
end
end
describe "create" do
it "Should create new all the partner links" do
get :create
end
end
describe "update" do
it "Should update all the partner links" do
get :update
end
end
describe "destroy" do
it "Should delete all the partner links" do
get :destroy
end
end
end
app/models/partner_link.rb--
class PartnerLink < ActiveRecord::Base
# attr_accessible :title, :body
validates_presence_of :name, :url, :description
end
This is my Gemfile--
source 'http://rubygems.org'
ruby '1.9.2'
gem 'rails', '3.2.11'
gem 'authlogic'
gem "devise"
gem "devise-encryptable"
gem "devise-async"
gem 'omniauth'
gem 'omniauth-facebook'
gem 'omniauth-twitter'
gem "cancan"
gem 'activemerchant'
gem 'aws-sdk'
gem 'aws-s3'
gem 'paperclip', '~> 3.0'
gem 'oauth2'
#gem 'fastercsv' #no-longer required after ruby 1.9
gem 'pg'
#gem 'thin'
gem 'unicorn'
gem 'simple_form'
gem 'haml-rails' # Use HAML instead of ERB for templates
gem 'friendly_id'
gem 'will_paginate'
gem 'will_paginate-bootstrap'
gem "nifty-generators", :group => :development
#gem "pdfkit"
gem "pdfkit", "~> 0.5.0"
gem 'wkhtmltopdf-binary'
gem 'wicked_pdf'
gem 'sendgrid', "~> 1.0.1"
gem 'delayed_job'
gem 'delayed_job_active_record'
gem 'bootstrap-datepicker-rails'
#gem 'roadie' #fixing email css
group :development, :test do
gem 'rspec-rails'
gem 'guard-rspec'
# Database Cleaner clears the database between tests. This done because we have
# to set config.use_transactional_fixtures = false in the spec_helper file.
# The use_transactional_fixtures value is set to false because Selenium test
# driver cannot access the test records created via database transactions.
gem 'database_cleaner'
end
group :test do
# gem 'factory_girl_rails'
gem 'capybara'
# As we’re using Capybara we can call the save_and_open_page method at any
# point and this will open the page in a browser so that we can take a look
# at it. This is enabled by Launchy.
# gem 'launchy'
# gem 'rspec-mocks'
end
gem "less-rails"
gem 'twitter-bootstrap-rails', '>= 2.0.3'
gem 'rb-readline', '~> 0.5.0', require: 'readline'
gem 'execjs'
gem 'therubyracer'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', " ~> 3.2.3"
gem 'coffee-rails', "~> 3.2.1"
gem 'uglifier', '>= 1.0.3'
end
gem "mail", "~> 2.4.4"
gem 'jquery-rails'
#gem "mocha", :group => :test
gem 'gmaps4rails'
gem 'acts_as_xlsx'
gem "httparty"
gem 'newrelic_rpm'
gem 'font_assets'
gem 'paper_trail', '~> 3.0.6'
gem 'mailchimp-api', require: 'mailchimp'
gem 'rack-ssl-enforcer'
gem 'ckeditor'
gem "rails_best_practices"
Related
I'm working on a piece of very old code (ruby 1.9.3 and rails 2.3.12). I'm trying to write some tests for it so that when I start upgrading it I have an idea of how everything is working. I'm writing them in cucumber at the moment and have come across an issue that I can't seem to solve. This issue does not appear in the production version as everything works fine on that. In the development AND test however, when I try and click one of the links, the following error appears;
And I click "Trips (1)" # features/step_definitions/user_management_steps.rb:1
SQLite3::SQLException: no such column: "id desc": SELECT "trips".* FROM "trips" INNER JOIN "trips_users" ON "trips".id = "trips_users".trip_id WHERE (("trips_users".user_id = 1)) ORDER BY ["id desc"] LIMIT 10 OFFSET 0 (ActiveRecord::StatementInvalid)
./vendor/plugins/geokit-rails/lib/geokit-rails/acts_as_mappable.rb:157:in `find'
./app/controllers/users_controller.rb:259:in `trips'
/home/camillavk/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/benchmark.rb:295:in `realtime'
<internal:prelude>:10:in `synchronize'
./features/step_definitions/user_management_steps.rb:2:in `/^I click "([^"]*)"$/'
features/trips.feature:30:in `And I click "Trips (1)"'
I've looked everywhere and cannot find any reference to
no such column: "id desc"
does anyone know what this means?
And why does this break in the development and test environments but not in the production environment?
Any help would be greatly appreciated!
*Edit
gemfile;
source 'https://rubygems.org'
gem "rails", "~> 2.3.12"
gem "airbrake"
gem "aws-s3"
gem "bj"
gem "calendar_date_select", "1.15"
gem "cancan", "1.2.0"
gem "carmen"
gem 'comma', '0.4.1'
gem 'exifr'
gem "factory_girl", "1.2.4"
gem 'fastercsv'
gem "geokit"
gem "haml"
gem "hpricot"
gem 'hoptoad_notifier'
gem "jrails"
gem "libxml-ruby", "2.4.0"
gem "memcached", "~> 1.8.0"
gem "mysql2", "~> 0.2.6"
gem "rake", "0.8.3"
gem 'recurly'
gem "rdoc"
gem "rmagick"
gem "rspreedly"
gem "rubyzip"
gem 'sass'
#need to use simplecov when upgrading to ruby 2 as rcov doesn't work
gem "simplecov"
gem 'sqlite3'
gem "will_paginate", "2.3.16"
gem 'yaml_db'
group :development, :test do
gem 'test-unit', '1.2.3'
gem 'rspec', '1.3.2'
gem 'rspec-rails', '~> 1.3.4'
end
group :test do
gem 'capybara', '0.3.5'
gem 'cucumber', '1.1.2'
gem 'cucumber-rails', :git => "git://github.com/RKelln/cucumber-rails.git", :branch => "0.3.2-capybara-fix"
gem 'database_cleaner'
end
user_controller.rb;
class UsersController < ApplicationController
before_filter :find_user
load_and_authorize_resource :except => [:news, :search, :update, :mobile_new, :mobile_success]
before_filter :authorise, :only => [:export_to_csv]
def find_user
begin
#user = User.find_by_login(params[:id])
rescue
#user = User.find(params[:id])
end
end
....
....
def trips
body_attributes "view-followers", 'main-feed', 'Trips'
#page = (params[:page].to_i || 0)
#page = 1 if #page == 0
#trips = #user.trips.reverse_order
#year = ''
#month = ''
unless params[:year].blank?
#year = params[:year].to_i
#trips = #trips.select { |trip| trip.start_date.year == #year }
end
unless params[:month].blank?
#month = params[:month].to_i
#trips = #trips.select { |trip| trip.start_date.month == #month }
end
#years = Array.new
unless #user.trips.empty?
#years = #user.trips.first.start_date.year..#user.trips.last.start_date.year
end
#show_more_link = #trips.count > (10 * #page)
#trips = #trips.paginate(:per_page => 10, :page => #page)
end
It looks like you have an order on your Trips query defined like this Trip.order('[id desc]'). The correct format is (depending on your Rails version):
Trip.order('id DESC')
Trip.order(id: :desc) # works only in Rails >= 4.0
I am a beginner in Ruby on Rails and I am writing a "User sign in" spec for a wiki project, and I am getting the following error:
uninitialized constant TestFactories (NameError)
This is my sign_in_spec.rb
require 'rails_helper'
describe "Sign in flow" do
include TestFactories
before do
#user = authenticated_user
end
describe "successful" do
it "redirects user to the wikis index" do
user = authenticated_user
visit root_path
end
end
end
This is my test_factories.rb file:
module TestFactories
def authenticated_user(options={})
user_options = { email: "email#{rand}#fake.com", password: 'password' }.merge(options)
user = User.new(user_options)
user.skip_confirmation!
user.save
user
end
end
This is my Gemfile:
source 'https://rubygems.org'
gem 'rails'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'bootstrap-sass', '~> 3.2.0'
gem 'autoprefixer-rails'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# Testing
group :develpment, :test do
gem 'rspec-rails'
gem 'capybara'
gem 'database_cleaner'
gem 'factory_girl_rails', '~> 4.0'
gem 'pry-rails'
end
# Databases
# Developemnt
gem 'sqlite3'
or you can do something like this in sepc helper
RSpec.configure do |config|
config.include TestFactories
end
I have a bookmarks resource and have mapped it to serve json by default under my api namespace like so in my routes.rb:
namespace :api, defaults: {format: 'json'} do
resources :bookmarks
get ':username', to: 'users#index'
get ':username/bookmarks/:id', to: 'users#show'
end
I have a Api::UsersController controller and a supporting BookmarkSerializer that works just fine on an individual bookmark resource like http://localhost:3000/api/emma_carter/bookmarks/87
But when I try to hit http://localhost:3000/api/emma_carter which is supposed to serve all bookmarks owned by the user, I get all different kinds of errors. Here is my Api::UsersController
module Api
class UsersController < ApplicationController
respond_to :json
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
render json: bookmarks
end
def show
user = User.find_by(username: params[:username])
bookmark = user.bookmarks.find_by(params[:id])
render json: bookmark
end
end
end
The show method works but the index method gives me ArgumentError in Api::UsersController#index
wrong number of arguments (1 for 0)
UPDATE: Full stack trace here: https://gist.github.com/amite/b79fc42bfd73de5a07bd
screenshot
Here is the serializer:
class BookmarkSerializer < ActiveModel::Serializer
attributes :id, :url, :title, :domain, :notes, :image, :created, :username
belongs_to :user
def created
object.created_at
end
def username
user.username
end
end
Looking at other solutions on stack overflow, I have also tried other versions of my index method:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
bookmarks.map { |bookmark| ::BookmarkSerializer.new(bookmark)}.to_json #updated line
end
This gives me the error:
Missing template api/users/index, application/index with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.
Next the last version of my index method looks like this:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
ActiveModel::ArraySerializer.new(bookmarks, each_serializer: ::BookmarkSerializer).to_json
end
This gives me the error uninitialized constant ActiveModel::ArraySerializer
What am I doing wrong? I am using rails 4.1.5 and the github version of the active_model_serializers
gem.
gem 'active_model_serializers', github: 'rails-api/active_model_serializers'
UPDATE: Since I am trying to output a collection of bookmarks I also tried using a separate serializer
BookmarksSerializer but I am getting the same error: ArgumentError in Api::UsersController#index
wrong number of arguments (1 for 0)
UPDATE2: Here is a version of the index method that kinda works in the sense that it renders the resource collection in json format:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
respond_with bookmarks.to_json
end
But this still does not use the BookmarksSerializer
class BookmarksSerializer < ActiveModel::Serializer
attributes :id, :title
end
It just outputs the default hash
Full Gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.5'
# Use mysql as the database for Active Record
gem 'mysql2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'bourbon'
gem 'neat'
gem 'bitters'
gem 'refills'
gem 'wisper'
gem 'rails-ioc'
gem 'reform'
gem 'cells'
gem "pundit"
gem 'active_model_serializers', github: 'rails-api/active_model_serializers'
gem "font-awesome-rails"
gem 'simple_form'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
# Call 'debugger' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
gem 'ffaker'
gem 'pry-rails'
gem 'capybara'
gem 'factory_girl_rails'
gem 'database_cleaner'
gem 'capybara-webkit'
gem 'rspec-cells'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-commands-rspec'
gem 'rspec-rails'
gem 'guard-rspec'
gem 'rb-fsevent' if `uname` =~ /Darwin/
end
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
turns out I need to include v0.9 of the gem
gem 'active_model_serializers', github: 'rails-api/active_model_serializers', branch: '0-9-stable'
you could try change:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
bookmarks.map { |bookmark| ::BookmarkSerializer.new(bookmark)}.to_json #updated line
end
to:
def index
user = User.find_by(username: params[:username])
bookmarks = user.bookmarks
render json: bookmarks.map { |bookmark| ::BookmarkSerializer.new(bookmark)}
end
I have no idea why I get the error when I click on "New Rating". And it seems creation of other models gives the same error.
Here's the error msg: "no member 'rating' in struct"
The error is on line 316 of inherited_resources-1.4.0/lib/inherited_resources/base_helpers.rb
Full stacktrace: https://gist.github.com/depy/5330548
313 # extract attributes from params
314 def build_resource_params
315 parameters = respond_to?(:permitted_params) ? permitted_params : params
316 rparams = [parameters[resource_request_name] || parameters[resource_instance_name] || {}]
317 if without_protection_given?
318 rparams << without_protection
319 else
320 rparams << as_role if role_given?
321 end
Here's my Rating model:
class Rating < ActiveRecord::Base
validates_uniqueness_of :task_id, :scope => [:user_id, :user_role], :message => 'You have already rated this task'
validates_inclusion_of :user_role, :in => %w( client contractor )
validates_presence_of :task_id, :user_id
validates_presence_of :score, :message => 'Please rate your satisfaction'
belongs_to :task
belongs_to :user
end
Here's my ActiveAdmin Rating.rb:
ActiveAdmin.register Rating do
controller do; include StrongAdmin; end
# list
index do
column :user_id
column :task_id
column :comment
column :score
default_actions
end
# single
show do |rating|
attributes_table do
row :id
row :rater do
task_id = Rating.find(params[:id]).task_id
div do
Task.find(task_id).client.full_name + " [" + Task.find(task_id).client.id.to_s+"]"
end
end
row :user
row :user_role
row :task
row :score
row :comment
row :created_at
end
active_admin_comments
end
end
Here's my Gemfile:
source 'https://rubygems.org'
ruby "1.9.3"
gem 'rails'
gem 'pg' # Database (PostgreSQL)
group :assets do
gem 'sass-rails'
gem 'uglifier'
gem 'bourbon'
gem 'jquery-fileupload-rails'
gem 'jquery-rails'
gem 'asset_sync'
end
group :production do
gem 'honeybadger'
gem 'newrelic_rpm' # App monitoring
end
gem 'bcrypt-ruby' # Secure passwords
gem 'devise' # Authentication
gem 'unicorn' # Webserver
gem 'redis'# Session storage and Task applications
gem 'carrierwave' # File uploading
gem 'mini_magick' # Image processing
gem 'kaminari'# Pagination
gem 'turbolinks' # Pushstate and async loading
gem 'strong_parameters' # Attribute accessible replacement
gem 'dalli' # Memcached interface
gem 'fog' # CDN connector
gem 'activeadmin' # (user) administration
gem 'cancan' # Authorization
gem 'gibbon' # Mailchimp API wrapper
gem 'multi_json'
gem 'nokogiri' # HTML parser for error messages
gem 'pusher' # Hosted websockets
gem 'sidekiq' # Async processing
gem 'draper' # Decorator
gem 'lograge' # Improved logger
gem 'slim'
gem 'sinatra', :require => nil
group :development do
gem 'sqlite3'
gem 'better_errors'
gem 'binding_of_caller'
gem 'meta_request'
gem 'quiet_assets'
end
group :test, :darwin do
gem 'rb-fsevent'
end
group :test do
gem 'rspec-rails'
gem 'factory_girl_rails'
gem 'capybara'
# gem 'capybara-webkit'
gem 'database_cleaner'
gem 'launchy'
gem 'faker'
end
I encountered the same issue. I updated ActiveAdmin from 0.5.1. to 0.6.0. The inherited resource gem was also updated to 1.4.0.
Since ActiveAdmin requires 1.3.1 or higher, you can lock the version in your gem
gem 'inherited_resources', "1.3.1"
This solved the issue for me.
I would like to test a controller that directly renders some JSON output (by using "render :json => #entity_names"). For that task I tried in my spec file "response.should have_text('["enim", "enita"]')". Unfortunately I always get that error:
Failure/Error: response.should have_text('["enim", "enita"]')
undefined method `has_text?' for #
Do I miss some gem that provides that method? Here my Gemfile:
source 'http://rubygems.org'
gem 'rails', '>= 3.0.0'
gem 'mysql2'
gem 'mongrel'
gem 'devise'
gem 'will_paginate', :git => 'git://github.com/mislav/will_paginate.git', :branch => 'rails3'
gem 'thinking-sphinx', :git => 'git://github.com/freelancing-god/thinking-sphinx.git', :branch => 'rails3', :require => 'thinking_sphinx'
group :test, :development do
gem 'rspec-rails', '>= 2.0.0.beta.19'
gem 'steak', :git => 'git://github.com/cavalle/steak.git'
gem 'webrat'
gem 'capybara'
gem 'capybara-envjs'
gem 'shoulda'
gem 'launchy'
gem 'autotest'
gem 'autotest-rails'
gem 'test_notifier'
gem 'rails3-generators'
gem 'factory_girl_rails'
gem 'populator'
gem 'faker'
gem 'random_data'
gem 'database_cleaner', :git => 'git://github.com/bmabey/database_cleaner.git'
gem 'delorean'
end
You could construct your expected output as JSON, then get the response body (which is also JSON), decode both, and compare them. Something like:
it "should do something" do
expected = { :some_key => "and some value" }.to_json
xhr :post, :create, { :foo => "bar" }
ActiveSupport::JSON.decode(response.body).should == ActiveSupport::JSON.decode(expected)
end