否定包含期望的自定义​​ RSpec 匹配器

Negating a custom RSpec matcher that contains expectations

我有一个自定义 RSpec 匹配器,用于检查作业是否已安排。它是这样使用的:

expect { 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) #does not work

为使上述工作正常,matches? 方法需要在未满足预期时 return false。问题是,即使它 return 是假的,期望值已经创建,因此测试错误地失败了。

关于如何制作这样的作品有什么想法吗?

我不得不寻找它,但我认为 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