覆盖action_controller.allow_forgery_protection以进行特定集成测试

and*_*ell 9 security testing integration-testing ruby-on-rails ruby-on-rails-3

我有一个protect_from_forgery在我的基本应用程序控制器中使用的rails3应用程序.我正在使用ActionDispatch::IntegrationTest并希望确保在某些集成测试期间存在真实性令牌.

我不希望执行帖子的每个功能测试都必须传递authenticity_token,所以我的test.rb文件指定:

  config.action_controller.allow_forgery_protection    = false
Run Code Online (Sandbox Code Playgroud)

正如rails文档所暗示的那样.

但是,对于集成测试,我希望确保我的表单正确发送真实性令牌.如果不全局更改设置,我找不到任何方法config/environments/test.rb

如果所有表单都是生成的,form_for我会满足于相信rails会处理这个,但是我使用ExtJS并且有许多需要手动指定的ExtJS表单,所以我真的应该测试管道是否全部工作.

Dam*_*kić 9

您只需更改集成测试设置中的值即可:

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
Run Code Online (Sandbox Code Playgroud)


gmc*_*ton 8

辅助方法,可以暂时阻止块的伪造:

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
Run Code Online (Sandbox Code Playgroud)