Rails:默认控制器规范失败

时间:2014-06-17 23:06:31

标签: ruby-on-rails ruby-on-rails-4 devise

我对Rails相当陌生,我试图让所有规格都通过。但是,其中一个默认规范失败,并出现以下错误:

Failures:

  1) RatingsController GET index assigns all ratings as @ratings
     Failure/Error: expect(assigns(:ratings)).to eq([rating])

       expected: [#<Rating id: 1, rottentomatoes_id: 1, rater_id: 1, rating: 10, created_at: "2014-06-17 22:58:53", updated_at: "2014-06-17 22:58:53">]
            got: nil

       (compared using ==)
     # ./spec/controllers/ratings_controller_spec.rb:34:in `block (3 levels) in <top (required)>'

Finished in 1 minute 34.34 seconds (files took 4.55 seconds to load)
61 examples, 1 failure

Failed examples:

rspec ./spec/controllers/ratings_controller_spec.rb:30 # RatingsController GET index assigns all ratings as @ratings

这是规范(它是由bundle exec rails generate scaffold ...生成的默认控制器规范):

RSpec.describe RatingsController, :type => :controller do
  include_context 'shared context'

  describe "GET index" do
    it "assigns all ratings as @ratings" do
      rating = Rating.create! valid_attributes
      get :index, {}, valid_session
      expect(assigns(:ratings)).to eq([rating])
    end
  end
end

shared_context

RSpec.shared_context 'shared context' do
  include Devise::TestHelpers
  include Warden::Test::Helpers
  Warden.test_mode!

  let(:user1) { User.find_by(id: 1)  || FactoryGirl.create(:user1) }
  let(:user2) { User.find_by(id: 2)  || FactoryGirl.create(:user2) }
  let(:user3) { User.find_by(id: 3)  || FactoryGirl.create(:user3) }
  let(:user4) { User.find_by(id: 4)  || FactoryGirl.create(:user4) }
  let(:admin) { Admin.find_by(id: 1) || FactoryGirl.create(:admin) }

  before do
    @admin = Admin.find_by(id: 1) || FactoryGirl.create(:admin)
    login_as(@admin, scope: :admin)
  end
end

我应该补充一点,我将Devise与控制器结合使用:

class RatingsController < ApplicationController
  before_action :set_rating, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!

  # GET /ratings
  # GET /ratings.json
  def index
    @ratings = Rating.all
  end
end

1 个答案:

答案 0 :(得分:-1)

我终于使用此链接找出了问题:https://github.com/plataformatec/devise/wiki/How-To:-Controllers-tests-with-Rails-3-(and-rspec)

该文档指出它适用于Rails 3,但我发现它也适用于Rails 4。