4

I'm at Rails Tutorial 7.4.4 and I'm curious about how the post_via_redirect method in the following test post form along with authenticity_token parameter.

The following test would pass:

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

In order to prevent CSRF (Cross Site Request Forgery), I assume that the form won't pass the verification without a correct authenticity_token parameter in the form. However, I cannot figure out from where the authenticity_token is put into the parameters.

In fact I'm not sure what exactly the POST in rails is doing. Would POST first request a web page of the URL to get the authenticity_token?

Godric Cao
  • 43
  • 3

1 Answers1

2

By default, the CSRF protection is disabled in the test environment. You can activate it by adding the following line in config/environments/test.rb:

config.action_controller.allow_forgery_protection = true

See the guide on Configuration Rails Application.

Baldrick
  • 23,882
  • 6
  • 74
  • 79