2

我有一组Tasks (即命令模式),它们被发送到线程列表中的作业调度程序。我想验证它是否接收到某个类别的Task( CreateTask,在本例中)。它们是通过 调度的perform_tasks!,它获取应该分配给线程的任务对象列表。

为了在 rspec 中进行测试,我设置了以下内容:

it "should dispatch a Create Task" do
    <... setup ... >

    TaskScheduler.should_receive(:perform_tasks!) do |*args|
        args.pop[0].should be_a CreateTask
    end

    <... invocation ... >
end

我找到match_aray(...)了,但我似乎无法弄清楚如何让它很好地测试它,因为它测试的是内容,而不是它们的类型。有没有更短或更好的方法来测试这个?基本上,有没有类似的东西:

TaskScheduler.should_receive(:perform_tasks!).with(array_containing_a(CreateTask))
4

1 回答 1

0

我不确定是否有一个现有的匹配器,但你可以很容易地为它编写一个自定义匹配器:

RSpec::Matchers.define :array_of do |expected|
  match do |actual|
    actual.map(&:class).uniq.should =~ Array(expected)
  end
end

TaskScheduler.should_receive(:perform_tasks!).with(array_of(CreateTask))

这将确保数组中的所有值都与传递的类型或类型数组匹配。如果您只想检查数组中的任何一个值是否与您的类型匹配,那也很容易:

RSpec::Matchers.define :array_containing_a do |expected|
  match do |actual|
    actual.map(&:class).should include expected
  end
end

TaskScheduler.should_receive(:perform_tasks!).with(array_containing_a(CreateTask))
于 2013-07-11T18:03:40.867 回答