Reputation: 2910
I'm experimenting with TDD and MiniTest. Now I want to test simple after_create
callback which will be pretty easy in RSpec but not so simple I guess with MiniTest. I've got below User
and Wallet
model:
class User < ApplicationRecord
after_create :create_wallet
has_one :wallet, dependent: :destroy
end
class Wallet < ApplicationRecord
belongs_to :user
end
How to test after_create
with MiniTest? I have my doubts whether I should be doing this at all but well... I think this is a part of TDD.
Upvotes: 1
Views: 761
Reputation: 3811
i think you should test that the method :create_wallet
will be called only one time
after a user created. Then for sure you could create another test case for the method :create_wallet
itself.
require "test_helper"
require "active_support/testing/method_call_assertions"
class UserTest < ActiveSupport::TestCase
include ActiveSupport::Testing::MethodCallAssertions
test "after create callback" do
user = User.new(...)
assert_called(user, :create_wallet, times: 1) do
user.save
end
end
test "create wallet" do
user = User.new(...)
assert_changes -> {user.wallet.blank?}, from: true, to: false do
user.save
end
# or assert_equal
user = User.create(...)
assert_equal Wallet.last.user_id, user.id
assert_equal 1, Wallet.where(user_id: user.id).count
end
end
Upvotes: 3