我正在尝试对我的 Controller 进行单元测试,每个使用 get
请求的测试都工作正常,但是我使用其他调用的测试(delete
in destroy , post
in create 和 put
in update) 失败并显示:
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 2.5ms
例如这是销毁测试:
test "should destroy blog" do
assert_difference('Blog.count', -1) do
delete :destroy, id: @blog
end
assert_redirected_to blogs_path
end
这是行不通的
这是对 show 的测试,有效:
test "should show blog" do
get :show, id: @blog
assert_response :success
end
在销毁测试中,authenticate_user!
只是将我重定向到登录页面,测试失败了。
最佳答案
显然在测试环境中禁用 CSRF token 是很正常的事情, 我补充说:
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
到我的“/config/environments/test.rb”文件,当前用户能够通过。
关于ruby-on-rails - rails 测试仅在 get 请求中传递 CSRF token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25207852/