ruby-on-rails - 使用元编程为多个工作人员编写单个规范

标签 ruby-on-rails ruby rspec

我写了一个 sidekiq worker 规范。所以现在我们有四个 worker ,规范几乎相同。所有规范都将测试 some_method 并检查作业是否已排队。

我的示例工作代码:

RSpec.describe HardWorker do
  subject(:worker) { described_class.new }

  describe "perform" do
    let(:some_id) { instance_double("String") }

    it "calls Hard working operation" do
      expect(HardWorkingOperation).to receive(:one_method)
        .with(some_id: some_id)

      worker.perform(some_id)
    end

    it "enqueues a HardWork worker" do
      HardWorker.perform_async(some_id)
      expect(HardWorker.jobs.size).to eq 1
    end
  end
end

第二个样本规范:

RSpec.describe AnotherWorker do
  subject(:worker) { described_class.new }

  describe "perform" do
    let(:key1){double("Integer")}
    let(:key2){double("String")}
    let(:options) do 
      {
        :key1 => key1, 
        :key2_ref => key2
      }
    end

    it "calls method_data" do
      expect(AnotherOperation).to receive(:another_method)
        .with(options["key1"], options["key2"])

      worker.perform(options)
    end

    it "enqueues a Another worker" do
        AnotherWorker.perform_async(options)
        expect(AnotherWorker.jobs.size).to eq 1
    end
  end
end

我想写一个单一的规范来测试所有接受某种方法的 worker (可以各自不同)并且该工作已经排队。 我怎样才能最好地做到这一点?有什么建议吗?

最佳答案

您可以使用 shared examples .假设它们都有一个“操作”类来执行调用,可能是这样的:

shared_examples_for "a sidekiq worker" do |operation_klass|
  subject(:worker) { described_class.new }

  describe "perform" do
    let(:some_id) { instance_double("String") }

    it "calls some operation" do
      expect(operation_klass).to receive(:call).with(some_id: some_id)
      worker.perform(some_id)
    end

    it "enqueues a worker" do
      described_class.perform_async(some_id)
      expect(described_class.jobs.size).to eq 1
    end
  end
end

RSpec.describe HardWorker do
  it_behaves_like "a sidekiq worker", HardWorkingOperation
end

如果您还需要检查 call 是否使用每个工作人员的一组不同参数完成,我想您可以将其作为散列传递。但到那时,你应该问问自己,是否真的应该提取该规范 :P

shared_examples_for "a sidekiq worker" do |operation_klass, ops_args|
  ..
  expect(operation_klass).to receive(:call).with(ops_args)
  ..
end

it_behaves_like "a sidekiq worker", HardWorkingOperation, { some_id: some_id }

关于ruby-on-rails - 使用元编程为多个工作人员编写单个规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45097017/

相关文章:

sql - 复杂用户匹配算法性能

ruby-on-rails - 如何在 App Engine 上运行 Ruby on Rails

ruby - ruby sinatra 中的补丁方法

ruby-on-rails - 运行 rspec 时如何让 Rails.logger 打印到控制台/stdout?

ruby-on-rails - 如何将 Evernote API 时间戳转换为 Postgresql 时间戳

ruby-on-rails - :default => 0 and :null => false differ for integer fields in migrations? 怎么办

ruby - 在 haml 中插入文本 block

ruby-on-rails - 将属性更新为 nil

ruby-on-rails - 预计 nil 不会成为新记录

ruby-on-rails - 应该::匹配器::独立::DelegateMethodMatcher:未定义的方法 `allow_nil'