Reputation: 1007
I'm sort of new to TDD, so you'll have to excuse me if this is obvious, but I've got a login system using Devise and Omniauth that works perfectly in development, but for some reason, when I run my rspec test, it fails.
I'm testing the create action for my authentications controller
class AuthenticationsController < ApplicationController
def create
omniauth = request.env['omniauth.auth']
authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authentication
flash[:notice] = "Signed in successfully"
sign_in_and_redirect(:user, authentication.user)
else
user = User.find_by_email(omniauth['info']['email']) || User.new(:email => omniauth['info']['email'], :fname => omniauth['info']['first_name'], :lname => omniauth['info']['last_name'])
user.authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
if user.save :validate => false
flash[:notice] = "Login successful"
sign_in_and_redirect(:user, user)
else
flash[:notice] = "Login failed"
redirect_to root_path
end
end
end
end
with this rspec test
describe "GET 'create'" do
before(:each) do
request.env['omniauth.auth'] = { "provider" => "facebook", "uid" => "1298732", "info" => { "first_name" => "My", "last_name" => "Name", "email" => "[email protected]" } }
end
it "should create a user" do
lambda do
get :create
end.should change(User, :count).by(1)
end
end
When I run the test I get
Failure/Error: get :create
NoMethodError:
undefined method `user' for nil:NilClass
# ./app/controllers/authentications_controller.rb:13:in `create'
Indeed, if I remove the sign_in_and_redirect statement, the test passes. Interestingly though, using sign_in instead of sign_in_and_redirect fails as well.
Anyone know why this might happen? Especially since when I create an account myself in development it works fine...
Thanks in advance for the help!
Upvotes: 3
Views: 1806
Reputation: 2482
How To: Controllers and Views tests with Rails 3 (and rspec)
Controller specs won’t work out of the box if you’re using any of devise’s utility methods.
As of rspec-rails-2.0.0 and devise-1.1, the best way to put devise in your specs is simply to add the following into spec_helper:
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
Upvotes: 1