I have a rails3 app that uses protect_from_forgery
in my base application controller. I'm using ActionDispatch::IntegrationTest
and want to ensure that authenticity tokens are present during certain integration tests.
I don't want every functional test that executes a post to have to pass up an authenticity_token
, so my test.rb
file specifies:
config.action_controller.allow_forgery_protection = false
as the rails docs suggest.
For integration tests, however, I'd love to make sure that my forms are sending up the authenticity token properly. I cannot find any way to do this without changing the setting globally in config/environments/test.rb
If all my forms were generated with form_for
I'd be content to trust that rails handles this, but I use ExtJS and have a number of ExtJS Forms that need to specify this manually, so I really should test that the plumbing is all working.
Helper method that enables forgery protection temporarily 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With