gpt4 book ai didi

ruby-on-rails - 如何使用 Rspec 和 FactoryGirl 在 Rails 模型中测试 before_update 回调?

转载 作者:行者123 更新时间:2023-12-01 14:02:14 25 4
gpt4 key购买 nike

我正在尝试测试模型波纹管的 before_update 回调。

模型/选项.rb:

class Option < ApplicationRecord
belongs_to :activity

has_many :suboptions, class_name: "Option", foreign_key: "option_id"

belongs_to :parent, class_name: "Option", optional: true, foreign_key: "option_id"

accepts_nested_attributes_for :suboptions, allow_destroy: true,
reject_if: ->(attrs) { attrs['name'].blank? }

validates :name, presence: true

before_create :set_defaults
before_update :set_updates


def set_defaults
self.suboptions.each do |sbp|
sbp.activity_id = self.activity_id
end
end

def set_updates
suboptions.each do |child|
child.activity_id = self.activity_id
end
end
end

规范/型号/option.rb:
require 'rails_helper'

RSpec.describe Option, type: :model do

describe "Callbacks" do
it "before_create" do
suboption = create(:option)
option = create(:option, suboptions:[suboption])
option.run_callbacks(:create) {false}
expect(option.suboptions.first.activity_id).to eq suboption.activity_id
end

it "before_update" do

end
end



end

我成功测试了 before_create 回调(至少它给了我正确的结果)。但我不知道如何测试 before_update 回调。有没有办法做到这一点?

最佳答案

警告:这个答案是自以为是。

测试行为,而不是实现。

回调是一个实现细节。不要直接测试。相反,假装您不知道模型在内部是如何工作的,然后测试它的行为方式。

如果我正确阅读代码,则行为可以这样描述:

When updating an option, the activity_id of each of its suboptions is set to the activity_id of the option.



创建一个带有子选项的选项。更新它,重新加载它,并检查每个activity_id 的值是否正确。

这将比模拟慢,但不那么脆弱。此外,测试更容易编写和维护。

关于ruby-on-rails - 如何使用 Rspec 和 FactoryGirl 在 Rails 模型中测试 before_update 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com