Override action_controller.allow_forgery_protection for a specific integration test

I have a rails3 application that uses protect_from_forgery in my base application controller. I use ActionDispatch::IntegrationTest and want authentication tokens to be present during certain integration tests.

I do not want every functional test that ran the message to pass authenticity_token , so my test.rb file indicates:

  config.action_controller.allow_forgery_protection = false 

as the rails offer.

However, for integration tests, I would like to make sure my forms send the authentication token correctly. I cannot find a way to do this without changing the settings globally in config/environments/test.rb

If all my forms were generated using form_for , I would be happy that the rails handle this, but I use ExtJS and have several ExtJS forms that should specify this manually, so I really have to check that the plumbing is working.

+7
source share
3 answers

You can simply change the value in your integration test setup:

 require 'test_helper' class MyCrunchyIntegrationTest < ActionController::IntegrationTest fixtures :all def setup ActionController::Base.allow_forgery_protection = true end def teardown ActionController::Base.allow_forgery_protection = false end test "how awesome my application is" do # ... end end 
+7
source

A helper method that temporarily protects against fraud for a block:

 def with_forgery_protection orig = ActionController::Base.allow_forgery_protection begin ActionController::Base.allow_forgery_protection = true yield if block_given? ensure ActionController::Base.allow_forgery_protection = orig end end with_forgery_protection do # code in here will require csrf token end 
+7
source

This is the version of RSpec @gmcnaughton.

This is in spec_helper.rb :

 RSpec.configure do |config| config.around(:each, :with_csrf_protection) do |example| orig = ActionController::Base.allow_forgery_protection begin ActionController::Base.allow_forgery_protection = true example.run ensure ActionController::Base.allow_forgery_protection = orig end end end 

Then you write tests, for example:

 it "foo", with_csrf_protection: true do # … end 

Or, depending on the RSpec settings:

 it "foo", :with_csrf_protection do # … end 
+1
source

All Articles