Search code examples
ruby-on-railsrubyrspecsidekiq

Rails specs for simple sidekiq delete worker failling


I've got simple sidekiq worker which, I don't know why it doesn't worked. I think maybe it's because of specs.

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

The admin_panel_log1 and admin_panel_log2 is corresponding model AdminPanelLog and it forms correctly (maybe I should avoid let! ?). At the result specs failed with an error

Failure/Error: expect(AdminPanelLog.count).to eq(1) expected: 1 got: 0 (compared using ==)


Solution

  • I justed tested with

    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
    

    The subject is initialized before the let! block is called. So in your case, the lo AdminPanelLog is not even created while the job was running. So that the example failed.

    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
    

    and remove this subject { described_class.new.perform }, as the subject itself will hold the value of the current class.