Rails MiniTest after_create 回调

Rails MiniTest after_create callback

我正在试验 TDD 和 MiniTest。现在我想测试简单的 after_create 回调,这在 RSpec 中会很容易,但我猜用 MiniTest 就没那么简单了。我有以下 UserWallet 型号:

class User < ApplicationRecord
  after_create :create_wallet

  has_one :wallet, dependent: :destroy
end


class Wallet < ApplicationRecord
  belongs_to :user
end

如何使用 MiniTest 测试 after_create?我怀疑我是否应该这样做,但很好......我认为这是 TDD 的一部分。

我认为您应该测试 :create_wallet 方法是否会在创建用户后被调用 only one time。那么你肯定可以为方法 :create_wallet 本身创建另一个测试用例。

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