Skip to content

Instantly share code, notes, and snippets.

@damien
Last active April 28, 2021 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damien/af43487dbb4b9d57e69a to your computer and use it in GitHub Desktop.
Save damien/af43487dbb4b9d57e69a to your computer and use it in GitHub Desktop.
Using MiniTest to mock and test ActiveRecord callbacks in Rails 4.2
class TeamMembership < ActiveRecord::Base
# A proc that will enqueue `NotificationMailer.team_invitation`
DEFAULT_NOTIFIER = proc do |user, team|
NotificationMailer.team_invitation(team, user).deliver_later
end
class << self
# This is a class level attribute that is mainly used for testing.
# Defaults to {TeamMembership::DEFAULT_NOTIFIER}
attr_accessor :notifier
end
self.notifier = DEFAULT_NOTIFIER
belongs_to :team
belongs_to :user
after_create :invite_user_to_team!
private
# ActiveRecord callback used to equeue team invitation emails
# @return void
def invite_user_to_team!
self.class.notifier.call(team, user)
nil
end
end
require 'test_helper'
class TeamMemberTest < ActiveSupport::TestCase
test 'callbacks' do
# setup
test_notifier = Minitest::Mock.new
test_notifier.expect(:call, nil, [teams(:alpha), users(:carol)])
TeamMembership.notifier = test_notifier
# test
TeamMembership.create(user_id: users(:carol).id, team_id: teams(:alpha).id)
assert test_notifier.verify
# teardown
TeamMembership.notifier = TeamMembership::DEFAULT_NOTIFIER
end
end
@benkoshy
Copy link

@damien, i appreciate the suggestions. I will implement as you've suggested. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment