I recently upgraded the RSpec version of my Rails 4 app. This is my setup:
# /Gemfile:
source 'https://rubygems.org'
group :development, :test do
gem 'rspec-rails', '~> 2.99'
...
end
# /spec/controllers/companies_controller_spec.rb:
require 'spec_helper'
describe CompaniesController, :type => :controller do
before(:all) do
@user = FactoryGirl.create(:user)
sign_in(@user)
end
describe 'GET #new' do
it "renders the :new view" do
get :new
expect(response).to render_template :new
end
end
...
end
# /spec/support/utilities.rb:
def sign_in(user)
cookies[:remember_token] = user.remember_token
end
The problem is that most of my tests are now failing and I've been trying to fix it for hours, but to no avail.
This is the error I get for nearly all tests that require a user
sign in:
Failure/Error: sign_in(@user)
NoMethodError:
undefined method `cookie_jar' for nil:NilClass
# ./spec/support/utilities.rb:2:in `sign_in'
The @user
object gets created by FactoryGirl, however. I've checked that in the test database and in the logs.
Why is my method for signing in users not working?
It worked like a charm before upgrading to a later version of RSpec.
Thanks for any help.
In a before(:all)
you shouldn't be doing stuff that only makes sense in the context of a single example.
In particular your sign_in
method fiddles with the cookies, which is implicitly the current request/controller's cookies. This doesn't make sense in a before(:all)
since each example is supposed to have a separate request - the exception occurs because there is no current request. Change the before(:all)
to a before(:each)
and you should be ok.
Rspec used to be more lenient in this respect, but 2.99 tightened this up, deprecation warnings were also added for similar uses in some of the earlier 2.x versions (if you had depreciations about using let/subject in a before(:all) block, that was it)