ruby-on-rails – Rails教程7.4.4 – post方法如何使用真实性令牌提交表单?

我在
Rails Tutorial 7.4.4,我很好奇以下测试帖子中的post_via_redirect方法与authenticity_token参数一起形成.

以下测试将通过:

class UsersSignupTest < ActionDispatch::IntegrationTest
  test "valid signup information will add user to database" do
    assert_difference 'User.count', 1 do
      post_via_redirect users_path, user: { name: "Filius Flitwick",
                               email: "Filius_Flitwick@Hogworts.ORG",
                               password:                "charmsmaster",
                               password_confirmation:   "charmsmaster" }
    end
  end
end

为了防止CSRF(跨站点请求伪造),我假设如果表单中没有正确的authenticity_token参数,表单将不会通过验证.但是,我无法弄清楚authenticity_token放在参数中的位置.

事实上,我不确定rails中的POST究竟是做什么的. POST会首先请求URL的网页以获取authenticity_token吗?

最佳答案 默认情况下,在测试环境中禁用CSRF保护.您可以通过在config / environments / test.rb中添加以下行来激活它:

config.action_controller.allow_forgery_protection = true

请参阅Configuration Rails Application的指南.

点赞