Last active
April 28, 2021 12:50
-
-
Save damien/af43487dbb4b9d57e69a to your computer and use it in GitHub Desktop.
Using MiniTest to mock and test ActiveRecord callbacks in Rails 4.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@damien, i appreciate the suggestions. I will implement as you've suggested. Thank you!