我有一个自定义 RSpec 匹配器,用于检查作业是否已安排。它的使用方式如下:
期望 { subject }.to Schedule_job(TestJob)
schedule_job.rb:
class ScheduleJob
include RSpec::Mocks::ExampleMethods
def initialize(job_class)
@job_class = job_class
end
...
def matches?(proc)
job = double
expect(job_class).to receive(:new).and_return job
expect(Delayed::Job).to receive(:enqueue).with(job)
proc.call
true
end
这对于正匹配来说效果很好。但它不适用于负匹配。例如:
expect { subject }.not_to Schedule_job(TestJob) #不起作用
要使上述工作正常进行,当未满足期望时,matches?
方法需要返回 false
。问题是,即使它返回 false,无论如何都会创建期望,因此测试会错误地失败。
关于如何使这样的事情发挥作用有什么想法吗?
最佳答案
我必须寻找它,但我认为 rspec documentation 中对此进行了很好的描述。
使用 expect.not_to
时的单独逻辑格式(来自文档):
RSpec::Matchers.define :contain do |*expected|
match do |actual|
expected.all? { |e| actual.include?(e) }
end
match_when_negated do |actual|
expected.none? { |e| actual.include?(e) }
end
end
RSpec.describe [1, 2, 3] do
it { is_expected.to contain(1, 2) }
it { is_expected.not_to contain(4, 5, 6) }
# deliberate failures
it { is_expected.to contain(1, 4) }
it { is_expected.not_to contain(1, 4) }
end
关于ruby-on-rails - 否定包含期望的自定义 RSpec 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51725805/