Rails集成测试-如何模拟不良的CSRF令牌和过期的会话 [英] Rails Integration Testing - How to Simulate bad CSRF token and Expired Session

查看:45
本文介绍了Rails集成测试-如何模拟不良的CSRF令牌和过期的会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just changed exception handling code in my application_controller.rb to correctly capture ActionController::InvalidAuthenticityToken.

我以前正在执行 rescue_from Exception ,该代码是在ActionController :: InvalidAuthenticityToken的recuse_from之后定义的.这是优先事项,我打算执行的抢救代码未执行.

I was previously doing a rescue_from Exception that was defined after the recuse_from ActionController::InvalidAuthenticityToken. This was taking priority and my intended rescue_from code was not being executed.

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

I'd like to write an integration test to verify this behavior. How can I create an object that will allow me to send a bad CSRF token to a post request to simulate this behavior?

我还希望有一个对象,该对象可以让我模拟过期的会话以发出get请求.我将如何实施这些集成测试?

I'd also like to have an object that will allow me to simulate an expired session to make a get request. How would I implement these integration tests?

推荐答案

可以使用以下方法模拟不良的CSRF令牌:

A bad CSRF token can be simulated with:

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

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

An expired session can be simulated using the TimeCop gem:

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

这篇关于Rails集成测试-如何模拟不良的CSRF令牌和过期的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆