Skip to content

Instantly share code, notes, and snippets.

@caike
Created June 18, 2013 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save caike/5807561 to your computer and use it in GitHub Desktop.
Save caike/5807561 to your computer and use it in GitHub Desktop.
Testing forgery protection. TIL Rails 3 changed the behavior of protect_from_forgery to just issue a WARNING.
class ApplicationController < ActionController::Base
protect_from_forgery
protected
def handle_unverified_request
super
raise ActionController::InvalidAuthenticityToken
end
end
require 'spec_helper'
describe JobsController do
it 'raises error with invalid authenticity token' do
with_forgery_protection do
expect { post :create }.to raise_error
end
end
private
def with_forgery_protection
_old_value = @controller.allow_forgery_protection
@controller.allow_forgery_protection = true
yield
ensure
@controller.allow_forgery_protection = _old_value
end
end
@jDeppen
Copy link

jDeppen commented Dec 18, 2016

I made this change to get Rails 5 working since ControllerTests now inherit from ActionDispatch::IntegrationTest

def with_forgery_protection
  ActionController::Base.allow_forgery_protection = true
  yield
ensure
  ActionController::Base.allow_forgery_protection = false
end

source: https://codingbunny.wordpress.com/2016/10/18/testing-csrf-and-custom-headers/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment