测试回调after_update rspec



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

用户.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不起作用。我说真了。我应该

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)>'

谢谢!

感谢伊扎拉文的回复。 最终运行正常的代码是:

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

谢谢

最新更新