Topic: Rspec and Session signin tokens
Basically I'm trying to figure out how to simulate a signed-in user in rspec.
My authentication system uses a "session[:user] = user.id" type of authentication. If you are familiar with Hartl's tutorial, I'm (loosely) working through it but using the Rails session token instead of the permanent cookie token.
I'm now trying to test a PUT to a create action that should only be accessible to the correct logged-in user (Section 9.2.2 of Hartl's Rails 3.2.3 Tutorial), but based on the errors I'm getting, it seems that the "sessions" method is not accessible using rspec.
My rspec code looks like this:
spec/requests/authentication_pages_spec.rb (this code seems to work ok):
describe "as wrong user" do
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: "wrong@example.com") }
before { sign_in user } # where sign_in is defined in the helper below
....
describe "submitting a PUT request to the Users#update action" do
before { put user_path(wrong_user) }
specify { response.should redirect_to(root_path) }
end
endspec/support/utilities.rb (the problem lies herein):
def sign_in(user)
# Capybara sign-in
visit signin_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
# Sign in when not using Capybara
session[:remember_token] = user.id # <---Problem code
endWhen I run the rspec, I get this error each time the sign-in action is called:
Failure/Error: sign_in user
NoMethodError:
undefined method `session' for #<User:0xa7c3ecc>
# ./spec/support/utilities.rb:17:in `sign_in'
# ./spec/requests/user_pages_spec.rb:78:in `block (3 levels) in <top (required)>'So where am I going wrong? What is the proper way to simulate a logged in user for a Rails session authentication system?
Thanks.
Last edited by Brian71 (2012-04-13 20:02:42)