Dimitar Kostov ramblings

Testing after_commit in rspec

mail_worker.rb
1
2
3
4
5
6
7
8
9
# app/workers/mail_worker.rb

class MailWorker
  include Sidekiq::Worker

  def perform(id)
    # send mail
  end
end
spec_helper.rb
1
2
3
4
5
6
7
# spec/spec_helper.rb

RSpec.configure do |config|
  config.use_transactional_fixtures = false

  # rest of the configuration
end
user.rb
1
2
3
4
5
6
7
8
9
10
11
# app/models/user.rb

class User < ActiveRecord::Base
  after_commit :send_welcome_mail, on: create

  private

  def send_welcome_mail
    MailWorker.perform_async(self.id)
  end
end
user_spec.rb
1
2
3
4
5
6
7
8
9
10
11
# spec/models/user_spec.rb

require 'spec_helper'

describe AffiliateProgram do
  let(:user) { FactoryGirl.create(:user) }

  it "should queue sending mail for user" do
    expect { user.run_callbacks(:commit) }.to change { AffiliateProgramOfferWorker.jobs.count }.by(1)
  end
end

Comments