[英]rails test passing CSRF token only in get requests
I'm trying to unit-test my controllers, every test that uses the get
request works fine, but the tests where I use other calls ( delete
in destroy, post
in create and put
in update) fail with a: 我试图单元测试我的控制器,使用的每个测试
get
请求工作正常,但如果我用其他电话(测试delete
的破坏, post
在创建和put
在更新)失败了:
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 2.5ms
for example this is the test for destroy: 例如,这是对破坏的测试:
test "should destroy blog" do
assert_difference('Blog.count', -1) do
delete :destroy, id: @blog
end
assert_redirected_to blogs_path
end
which doesn't work 这不起作用
and this is the test for show, which works: 这是show的测试,它起作用:
test "should show blog" do
get :show, id: @blog
assert_response :success
end
in the destroy test the devise authenticate_user!
在破坏测试中,设计
authenticate_user!
just redirects me to the sign_in page and the test fails. 只是将我重定向到sign_in页面,测试失败。
Apparently it's a normal thing to disable the CSRF token in the test environment, I added: 显然,在测试环境中禁用CSRF令牌是正常的,我补充说:
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
to my "/config/environments/test.rb" file and the current user was able to pass through. 到我的“/config/environments/test.rb”文件,当前用户能够通过。
To get by authenticate_user!
通过
authenticate_user!
获取authenticate_user!
, you'll need to include and use the Devise test helpers as shown here: ,您需要包含并使用Devise测试助手,如下所示:
https://github.com/plataformatec/devise#test-helpers https://github.com/plataformatec/devise#test-helpers
class ActionController::TestCase
include Devise::TestHelpers
end
And use them in your tests: 并在您的测试中使用它们:
test "should show blog" do
@user = users(:one) # or FactoryGirl.create(:user), or User.create!(email: 'foo@bar.com')
sign_in @user
get :show, id: @blog
assert_response :success
end
As for the CSRF Token, is your form built using form_for
or some other form-builder? 对于CSRF令牌,您的表单是使用
form_for
还是其他一些表单构建器构建的?
These automatically add the CSRF token to your form payload. 这些会自动将CSRF令牌添加到表单有效内容中。 If you are writing your forms with bare
<form>
tag markup, you'll have to add it to the form yourself like this: 如果您使用裸
<form>
标记标记编写表单,则必须将其自己添加到表单中,如下所示:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.