2017-02-11 47 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语法产生警告不显式启用的语法已经过时了。