Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All Ruby tests raising: undefined method `authenticate' for nil:NilClass

This question has been answered on Twitter by @MatthewClosson

@jeffehh You need to create a spec/support/devise.rb file as specified here https://github.com/plataformatec/devise#test-helpers to include the devise test helpers #ruby

Thanks once again.


I'm aware you're using Rspec but you can run into this same issue with Test::Unit. You just need to add the devise test helpers to test/test_helper.rb

class ActiveSupport::TestCase
  include Devise::TestHelpers
end

in RSpec

as Jeffrey W. mentioned, in his answer above -> to set this to all controllers:

RSpec.configure do |config|
  # ...
  config.include Devise::TestHelpers, type: :controller
  # ...
end

however, if this is relevant to just one spec, you don't necessarily need to include devise helpers to all your controllers specs, you can just explicitly include those helpers in that one controller describe block:

require 'spec_helper'
describe MyCoolController
  include Devise::TestHelpers

  it { } 
end

The above answer did not work for me (RSpec 3.1)

See https://stackoverflow.com/a/21166482/1161743 for a solution that worked for me.

You will need to log out an anonymous user before setting up variables:

before :each do
  sign_out :user
end

I was experiencing the same failures in one of my projects. It is using Ruby 2.0.0-p598, Rails 3.2.21, RSpec 2.99. When I run all specs together the problem occurred. When I ran the specs individually, they passed. I have the following included in my spec/spec_helper.rb:

RSpec.configure do |config|
  # ...
  config.include Devise::TestHelpers, type: :controller
  # ...
end

I added the following to the first describe in each failing spec file. This did not resolve the problem:

before :each do
  sign_out :user
end

Neither did:

after :each do
  sign_out :user
end

Taking inspiration from the answer to this stackoverflow question, I ran different combinations of rspec directories together to find out which ones could be interfering with each other. In the end I discovered I was calling:

before() do #note no :each passed to before
  :
end

when I changed all occurrences of this to:

before(:each) do
  :
end

All the specs passed without the failure:

undefined method `authenticate' for nil:NilClass

I hope this is of help to others.