How to access session from Rails Integration Test?

2019-04-05 16:00发布

Consider the following integration test:

test "if there is no user in session, redirect to index and flash message" do
  open_session do |sess|
    post '/login', :email => users(:client).email, :password => 'rumpelstiltskin'
    sess[:user] = nil
    get '/user_page'
    assert_redirected_to index_path
    assert_equal "Your session has expired. Please log in again", flash[:notice]
  end    
end

This generates error: undefined method '[]='

And, changing to sess.session[:user] = nil generates an error as well: NoMethodError: undefined method 'session' for nil:NilClass

How do you modify the session params from an integration test in Rails?

Working in Rails 3.0.7, Ruby 1.9.2p180, Unit test framework.

EDIT:
get '/user_page', nil, {:user => nil} and get ('/user_page', nil, {:user => nil} ) generate errors.

4条回答
Anthone
2楼-- · 2019-04-05 16:28

It turns out that it does not seem possible to do this.

查看更多
相关推荐>>
3楼-- · 2019-04-05 16:29

Just use session[:user] without open_session block

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-04-05 16:48

In Rails 3.2.3 the following seems to work for me:

# Hit the root_path to start our session
get root_path

# A helper method to set our session
login_as(@user_fixture)

# Now we can access the session variable
assert session[:user_id]

Not sure if this will work for you, so goodluck!

查看更多
霸刀☆藐视天下
5楼-- · 2019-04-05 16:48

This isn't what integration tests are designed for. You shouldn't modify the session directly, instead you should hit your /logout path.

查看更多
登录 后发表回答