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



我有一个自定义的 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?方法需要在未满足预期时返回false。问题是,即使它返回 false,无论如何都已经创建了期望,因此测试错误地失败了。

关于如何使这样的东西工作的任何想法?

我不得不寻找它,但我认为它在 rspec 文档中得到了很好的描述

使用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

最新更新