加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 无法在Rails 5控制器测试中设置会话哈希

发布时间:2020-12-17 04:15:36 所属栏目:百科 来源:网络整理
导读:根据 Rails Edge Guide,所有ActionDispatch :: IntegrationTest HTTP请求都采用可选的命名关键字参数: get post_url,params:{id:12},session:{user_id:5} 大.现在,我在控制器测试中得到以下代码: test 'should redirect from login page if user is lo
根据 Rails Edge Guide,所有ActionDispatch :: IntegrationTest HTTP请求都采用可选的命名关键字参数:

get post_url,params:{id:12},session:{user_id:5}

大.现在,我在控制器测试中得到以下代码:

test 'should redirect from login page if user is logged in' do
  get '/login',session: { user_id: users(:stephen).id }
  assert_redirected_to root_url,'Expected redirect to root'
end

当我运行它时,我的测试失败,我看到以下弃用警告:

ActionDispatch::IntegrationTest HTTP request methods will accept only
the following keyword arguments in future Rails versions:
params,headers,env,xhr

所以显然它的rails不会让我传递一个名为session的关键字参数.

此外,在功能测试中设置会话的两种旧方法都不再有效:

test "some thing" do
  session[:user_id] = users(:stephen).id
  # etc
end

NoMethodError: undefined method `session’ for nil:NilClass

这也失败了:

test "some thing" do
  get '/login',nil,{ user_id: users(:stephen).id }
  # etc
end

只会忽略会话哈希,并且会显示有关仅接受4个不同命名参数的rails的弃用警告.

是否有其他人在使用Rails 5.rc1时遇到这种麻烦?

解决方法

在Rails 5中,不再可能在控制器测试中访问会话: http://blog.napcs.com/2016/07/03/upgrading-rails-5-controller-tests/.建议访问将为您设置适当会话值的控制器方法.此评论显示了您如何解决此限制的示例: https://github.com/rails/rails/issues/23386#issuecomment-192954569
# helper method
  def sign_in_as(name)
    post login_url,params: { sig: users(name).perishable_signature )
  end

class SomeControllerTest
  setup { sign_in_as 'david' }

  test 'the truth' do
  ..

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读