【问题标题】:Rails Integration Testing - How to Simulate bad CSRF token and Expired SessionRails 集成测试 - 如何模拟错误的 CSRF 令牌和过期会话
【发布时间】:2014-12-19 07:10:23
【问题描述】:

我刚刚更改了 application_controller.rb 中的异常处理代码以正确捕获 ActionController::InvalidAuthenticityToken

我之前在做一个rescue_from Exception,它是在recuse_from ActionController::InvalidAuthenticityToken 之后定义的。这是优先考虑的,我的预期rescue_from代码没有被执行。

我想编写一个集成测试来验证这种行为。如何创建一个对象,允许我将错误的 CSRF 令牌发送到发布请求以模拟此行为?

我还想要一个对象,让我可以模拟过期会话来发出获取请求。我将如何实施这些集成测试?

【问题讨论】:

  • 您可以简单地存根verified_request? 以返回false。

标签: session ruby-on-rails-4 integration-testing csrf


【解决方案1】:

可以使用以下方法模拟错误的 CSRF 令牌:

with_forgery_protection do
    post user_session_path, {:authenticity_token => 'foo'}
    assert redirected_to_new_user_session_path
end

可以使用 TimeCop gem 模拟过期会话:

Timecop.travel 2.days.from.now do
    get some_authorized_path
    assert_redirect_to new_user_session_path
end

【讨论】:

    猜你喜欢
    • 2011-12-06
    • 2011-09-30
    • 2015-01-04
    • 2015-08-15
    • 1970-01-01
    • 2021-02-24
    • 2018-07-12
    • 2016-09-03
    • 2017-07-15
    相关资源
    最近更新 更多