【问题标题】:In a Rails controller test, how to access a different controller action?在 Rails 控制器测试中,如何访问不同的控制器操作?
【发布时间】:2014-03-29 01:34:00
【问题描述】:

在功能测试中,我想在另一个控制器中调用一个动作。

【问题讨论】:

标签: ruby-on-rails testing controller functional-testing


【解决方案1】:

您必须@controller 实例变量设置为应该使用的控制器。

测试辅助方法中的示例用法(当然您不需要在辅助方法中使用它 - 您可以在测试方法中直接使用它):

def login(user_name='user', password='asdfasdf')

    # save the current controller
    old_controller = @controller

    # use the login controller
    @controller = LoginController.new       # <---

    # perform the actual login
    post :login, user_login: user_name, user_password: password
    assert_redirected_to controller: 'welcome', action: 'index'

    # check the users's values in the session
    assert_not_nil session[:user]

    assert_equal session[:user], User.find_by_login('user')

    # restore the original controller
    @controller = old_controller

end

由 Jonathan Weiss 于 2006 年在 ruby​​-forum 上回答:post() to other controller in functional test?

应该注意的是,在大多数情况下(可能 >99.9% 的时间),应该使用集成测试(也称为功能测试)来测试控制器间的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 2020-02-16
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多