5

我将 rspec 从版本 2 升级到了 3。之后我遇到了这个问题:

Failures:

  1) AlbumsController GET #edit 
     Failure/Error: sign_in_and_switch_schema @user
     NoMethodError:
       undefined method `env' for nil:NilClass
     # ./spec/support/auth_helpers.rb:10:in `sign_in_and_switch_schema'
     # ./spec/controllers/albums_controller_spec.rb:12:in `block (2 levels) in <top (required)>'

spec_helper.rb包含:

 RSpec.configure do |config|
    # most omitted
    config.include Warden::Test::Helpers
    config.include Devise::TestHelpers, type: :controller
 end

Albums_controller_spec.rb

describe AlbumsController do

  let(:album) { create(:album) }

  before(:all) do
    @user = create :user
  end

  before(:each) do
    sign_in_and_switch_schema @user
  end

  after(:all) do
    destroy_users_schema @user
    destroy_user @user
  end

 # describe's part omitted
end

发生错误的auth_helpers.rb部分:

def sign_in_and_switch_schema(user)
 # binding.pry
 @request.env["devise.mapping"] = Devise.mappings[:user] # <- error line
 sign_in :user, user

 Apartment::Tenant.switch(user.username) 
end

我正在寻找另一个类似的问答,但没有发现任何帮助。让我知道我是否应该包含更多内容。提前致谢。

4

2 回答 2

7

解决方案是添加到 spec_helper.rb:

RSpec.configure do |config|
    config.infer_spec_type_from_file_location!
end
于 2014-08-13T07:28:48.037 回答
3

According to the Devise TestHelper documentation, you should only be using

@request.env["devise.mapping"] = Devise.mappings[:user]

when you are testing a controller that inherits a Devise controller. I guess the AlbumsController doesn't inherits from a Devise Controller. I don't think you need that line for these tests.

Try removing this line or creating another helper method that does only the sign_in and the switch:

def simple_sign_in_and_switch(user)
  sign_in :user, user
  Apartment::Tenant.switch(user.username)
end

And then call that method instead in your test case:

before(:each) do
  simple_sign_in_and_switch_schema @user
end

If this works try removing the faulty line completely and run your full test suite to see if it is needed somewhere else. If it is, extract that line in another method and use it only when you need.

于 2014-08-12T19:57:21.687 回答