【问题标题】:How to access session from Rails Integration Test?如何从 Rails 集成测试访问会话?
【发布时间】:2011-12-30 16:34:19
【问题描述】:

考虑以下集成测试:

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

这会产生错误:undefined method '[]='

而且,更改为 sess.session[:user] = nil 也会产生错误:NoMethodError: undefined method 'session' for nil:NilClass

如何从 Rails 的集成测试中修改会话参数?

使用 Rails 3.0.7、Ruby 1.9.2p180、单元测试框架。

编辑:
get '/user_page', nil, {:user => nil}get ('/user_page', nil, {:user => nil} ) 生成错误。

【问题讨论】:

  • 这是单元测试还是集成测试? :)

标签: ruby-on-rails ruby-on-rails-3 unit-testing session integration-testing


【解决方案1】:

这不是集成测试的目的。您不应该直接修改会话,而应该点击 /logout 路径。

【讨论】:

  • 是的,但问题是关于访问session
  • @BorisStitnicky - 是的,我说不要访问会话,这是错误的。这是我两年前写的,但我想我仍然坚持。
【解决方案2】:

在 Rails 3.2.3 中,以下似乎对我有用:

# 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]

不确定这是否适合你,祝你好运!

【讨论】:

    【解决方案3】:

    事实证明,这样做似乎是不可能的。

    【讨论】:

      【解决方案4】:

      只需使用 session[:user] 而不使用 open_session

      【讨论】:

      • session[:user] = nil 不会将更新后的会话传递给控制器​​。
      • 这适用于 rails 2,但不适用于 rails 3(这是问题中使用的版本)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多