7

我有一個rails3應用程序,在我的基本應用程序控制器中使用protect_from_forgery。我正在使用ActionDispatch::IntegrationTest,並希望確保在某些集成測試期間存在真實標記。覆蓋action_controller.allow_forgery_protection特定的集成測試

我不希望每個功能測試執行後有傳遞了一個authenticity_token,所以我test.rb文件規定:

config.action_controller.allow_forgery_protection = false 

的軌道文檔建議。

但是,對於集成測試,我想確保我的表單正確發送真實性標記。我找不到任何方式做到這一點,而不在全球變化中的設置config/environments/test.rb

如果有form_for生成所有我的形式,我會滿足於相信軌處理這個,但我使用ExtJS的,並有一些ExtJS的形式需要手動指定,所以我真的應該測試管道工作是否正常。

回答

7

你可以簡單地在集成測試設置中更改數值:

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 
+1

但這並不重置它爲下一個測試!國際海事組織gmcnaughton的答案是更好的。 – 2014-09-16 17:43:11

+1

是的。編輯以重置「拆卸」方法中的值。不過,使用塊作爲@gmcnaughton建議可能更適合更細化的控制。 – 2014-09-17 09:56:28

7

助手方法,使防僞保護暫時塊:

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 
1

這是@ gmcnaughton的解決方案的RSpec的版本。

這正好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 
    end 
end 

然後你寫的測試,如:

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

,或者根據您的RSpec設置:

it "foo", :with_csrf_protection do 
    # … 
end