Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override action_controller.allow_forgery_protection for specific integration test

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.

like image 470
andrewmitchell Avatar asked May 06 '11 23:05

andrewmitchell


2 Answers

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
like image 86
gmcnaughton Avatar answered Nov 05 '22 05:11

gmcnaughton


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
like image 28
Damir Zekić Avatar answered Nov 05 '22 03:11

Damir Zekić