测试回调 after_update rspec

testing callbacks after_update rspec

我有 2 个模型 User.rbClient.rb。关系是:

User.rb

has_and_belongs_to_many :clients, inverse_of: :users

客户端

has_and_belongs_to_many :users, inverse_of: :clients

User.rb 模型中的回调

after_create :client_not_erasable
after_update :assign_client


def client_not_erasable
.
.
end

def assign_client
  def to_param
    return Client.find(client_to_add) unless client_to_add.nil?
  end
  unless client_to_add.nil?
    if to_param.users.count.zero? && client_to_add.present?
      to_param.update_attributes(erasable:false)
    end
  end
end

第一个回调 after_create :client_not_erasable 工作正常,但第二个回调 after_update :assign_client 不工作。我说实话了。我应该得到 false

挂钩

describe 'after_save and after_update callbacks' do
  let(:user) { build(:user) }
  let(:client) { build(:client) }
  it 'erasable client field should be false after of an user create' do
    user.clients.count == 1
    user.clients[0].erasable = true
    user.run_callbacks :create
    expect(user.clients[0].erasable).to be(false)
  end
  it 'erasable client field should be false after of it is assigned to user' do
    client.erasable = true
    user.run_callbacks :update
    expect(client.erasable).to be(false)
  end
end

检测结果:

Failures:

  1) User Validations after_save and after_update erasable client field should be false after of it is assigned to user
     Failure/Error: expect(client.erasable).to be(false)

       expected false
            got true
     # ./spec/models/user_spec.rb:93:in `block (4 levels) in <top (required)>'

谢谢!

感谢 yzalavin 的回复。最终运行良好的代码是:

挂钩

context 'Hooks' do
  let(:client) { build(:client) }
  let(:user) { build(:user) }
  let!(:users) { create_list(:user, 2, clients: [client]) } 
  it 'erasable client field should be false after of an user create' do
    user.clients.count == 1
    user.clients[0].erasable = true
    user.run_callbacks :create
    expect(user.clients[0].erasable).to be(false)
  end
  it 'erasable client field should be false after of it is assigned to user' do
    client.erasable = true
    user.run_callbacks :update
    expect(client.reload.erasable).to be(false)
  end
end

谢谢