Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `env' for nil:NilClass

I upgraded rspec from version 2 to 3. After that I faced that problem:

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 contains:

 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 part on which error occurred :

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

I was looking for another simmilar Q&A but found nothing helped. Let me know if I should include something more. Thanks in advance.

like image 560
pawel7318 Avatar asked Aug 12 '14 17:08

pawel7318


Video Answer


2 Answers

Solution was to add to spec_helper.rb:

RSpec.configure do |config|
    config.infer_spec_type_from_file_location!
end
like image 145
pawel7318 Avatar answered Oct 06 '22 01:10

pawel7318


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.

like image 39
Marc Lainez Avatar answered Oct 06 '22 00:10

Marc Lainez