1

我有一个简单的 sidekiq 工人,我不知道为什么它不起作用。我想可能是因为规格。

worker

class AdminPanelLogRemoverWorker
  include Sidekiq::Worker

  def perform
    expired_logs = AdminPanelLog.where('created_at > ?', 1.year.ago)
    expired_logs.delete_all
  end
end

specs

require 'rails_helper'

describe AdminPanelLogRemoverWorker do
  include_context 'with admin_user form'

  subject { described_class.new.perform }

  let!(:admin_panel_log1) do
    create :admin_panel_log,
    action_type: 'Update',
    old_data: admin_user_form,
    created_at: 2.years.ago
  end
  let!(:admin_panel_log2) do
    create :admin_panel_log,
    old_data: admin_user_form,
    created_at: 2.days.ago
  end

  context 'when admin log is outdated' do
    it 'calls remover worker' do
      expect(AdminPanelLog.count).to eq(1)
    end
  end
end

admin_panel_log1and是相应的admin_panel_log2模型AdminPanelLog,它形成正确(也许我应该避免let!?)。结果规范失败并出现错误

失败/错误:expect(AdminPanelLog.count).to eq(1) expected: 1 got: 0 (比较使用 ==)

4

2 回答 2

1

我刚刚测试过

RSpec.describe TestController, type: :controller do

    subject { User.new }

    let!(:test) do
      p subject
      p "dfvb"
    end

    it 'testing order of let and subject' do 
      # Spec
     end
end

在调用块subject之前初始化。因此,在您的情况下,甚至在作业运行时都没有创建let!lo 。AdminPanelLog所以这个例子失败了。

context 'when the admin log is outdated' do
    it 'calls remover worker' do
      subject.new.perform #Perform the job here or after the initialization of AdminPanelLog 
      expect(AdminPanelLog.count).to eq(1)
    end
  end

并删除 this subject { described_class.new.perform },因为主题本身将保存当前类的值。

于 2019-09-13T08:31:35.500 回答
0

正如 Aarthi 的回答已经表明的那样,问题是您没有调用主题,因此没有执行代码并且没有调用您的工作人员。不过,我会通过以下方式改进答案

context 'when admin log is outdated' do
    it 'remover worker deletes them' do
      expect { subject }.to change(AdminPanelLog, :count).by(-2) #or whatever the amount is
    end
  end

上面的测试允许你检查工人是否确实完成了删除内容的工作。

于 2019-09-13T14:20:24.223 回答