2017-02-11 46 views
1

我有一個自定義的匹配,即有一個expect內:RSpec的:否定自定義內強制錯誤匹配器

RSpec::Matchers.define :have_access_to do |action| 
    match do |user| 
    allow(controller).to receive(:authorize!) 

    # perform GET request... 

    expect(controller).to have_received(:authorize!) 

    response.code == "200" 
    end 
end 

這個工作,只要我把它叫做這樣

it { expect(shop_manager).to have_access_to(:index) } 

但是,當我嘗試用否定形式not_toexpect客戶內匹配失敗,測試通過:

it { expect(shop_manager).not_to have_access_to(:index) } 

我在這裏理解RSpec邏輯:當你想測試失敗與not_to,它失敗了,一切都很好。

但是這個expect作爲一個副條件:我想檢查整個請求是否已通過authorize!步驟。

我知道一個匹配器應該只測試一件事,但我使用它很多,當我將have_received(:authorize!)檢查添加到每個單個測試時,它會導致很多代碼重複。

有沒有辦法強制RSpec失敗,無論是否否定呼叫?

回答

1

你可以做

RSpec::Matchers.define :have_access_to do |action| 
    match do |user| 
    allow(controller).to receive(:authorize!) 

    # perform GET request... 
    fail "failed to receive authorize" unless controller.received_message?(:authorize!) 

    response.code == "200" 
    end 
end 

使用舊的RSpec早該語法。不過,我得到這個

使用received_message?從RSpec的,嘲笑的老:should語法產生警告不顯式啓用的語法已經過時了。