2016-06-13 76 views
6

会议哈希按照Rails Edge Guide所有ActionDispatch :: IntegrationTest HTTP请求的随意命名关键字参数:无法设置在导轨5控制器测试

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不让我传递一个名为会话的关键字参数。

此外,两者在功能测试设置会话的老办法不再工作,要么:

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, nil, { user_id: users(:stephen).id } 
    # etc 
end 

会话哈希只是忽略了,关于rails的弃用警告只出现了4个不同的命名参数。

是否有其他人对Rails 5.rc1有这种麻烦?

+0

根据示例'得到POST_URL,则params:{ID:12},会话:{USER_ID:5}'第二个参数是* params *,'get'/ login',session:{user_id:users(:stephen).id}'但是你通过* session *,你尝试了'get'/ login',params:{} user_id:users(:stephen).id}'? –

+0

@Зелёный参数都是完全可选的,顺序不重要,是的,我确实尝试了你的想法,但它没有解决问题 – stephenmurdoch

+0

这很奇怪,因为在我的测试中顺利运行 –

回答

1

尽量设置session通过open_session方法

open_session do |sess| 
    sess.get "/login", user_id: users(:stephen).id 
    assert_redirected_to root_url, 'Expected redirect to root' 
end 
+0

'params!= session' –

+0

@stephenmurdoch我已经刷新了我的答案,你可以试试吗 – itsnikolay

+0

感谢@itsnikolay它看起来像Rails中有一个错误,我的答案解释了更多。 – stephenmurdoch

1

事实证明,控制器的测试,现在从ActionDispatch::IntegrationTest默认和handles the behaviour I wanted坐在ActionController::TestCase代码继承。

所以现在的解决方法是做到以下几点:

1 - 修改控制器测试从继承的ActionController :: TestCase的

class SessionsControllerTest < ActionController::TestCase 

2 - 修改所有HTTP请求的调用来使用符号化的动作名称而非网址:

# so change this 
get login_url 

# to this 
get :new 

然后你应该能够使用新的kw_args在您的要求,像这样:

# now this will work fine 
get :new, session: { user_id: user.id } 

# and so will this 
session[:user_id] = user.id 

我打算在后面的github上打开一个问题,因为我想象这种行为并不打算。由于@BoraMa领导我的答案

+2

我为此创建了一个问题[https://github.com /导轨/导轨/问题/ 25394) – stephenmurdoch

0

我认为你可以因为这样做:

delete cart_url(@cart), params: { 'session' => { :cart_id => @cart.id }} 
6

在Rails五是不再可能在控制测试访问会话: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 
    ..