Rails Integration Testing - How to Simulate bad CSRF token and Expired Session

核能气质少年 提交于 2020-01-23 22:47:08

问题


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

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.

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?

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/26531101/rails-integration-testing-how-to-simulate-bad-csrf-token-and-expired-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!