Override action_controller.allow_forgery_protection for specific integration test Override action_controller.allow_forgery_protection for specific integration test ruby-on-rails ruby-on-rails

Override action_controller.allow_forgery_protection for specific integration test


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  endendwith_forgery_protection do  # code in here will require csrf tokenend


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    # ...  endend


This is a RSpec version of @gmcnaughton's solution.

This goes 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  endend

Then you write the tests like:

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

Or, depending on your RSpec settings:

it "foo", :with_csrf_protection do  # …end