Starkers
Starkers

Reputation: 10541

Access session inside spec

I have this simple helper found at spec/helpers/session.rb:

def sign_in user
    session[:remember_token] = user.remember_token
end

However, I get an error when I try to use it in a spec. The following:

context 'when user is is signed in' do
    before do 
        sign_in user
        request 
    end

    specify{ expect(flash[:success]).to eq "Signed out successfully" }
end

gives me:

Failure/Error: sign_in user
NameError:
undefined local variable or method `session' for #<RSpec::ExampleGroups::AdminArea::Authentication::GuestVisitsRoot:0x00000004f835f0>

So how can I manipulate the session from inside a spec? Is it possible?

Upvotes: 3

Views: 318

Answers (1)

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8122

I believe you are seeing this error in integration test. Integration tests aren't designed for checking session related things.

You can achieve same thing in this way

def sign_in user
    # you can also use 
    # something like this 
    # post signin_path, :login => user.login, :password => 'password'
    # but i dont recommend this, since this is not how user do it.
    visit sign_in_path
    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Sign in'
end 

And then in test, something like

 expect(page).to have_content('My Account')

There are many great answer available . Have a look, if you have any problem..include it in question i will try to answer

  1. session available in some rspec files and not others. how come?

  2. Stubbing authentication in request spec

  3. End-to-End Testing with RSpec Integration Tests and Capybara

Upvotes: 6

Related Questions