Ruby on rails 销毁回调前的Rspec

Ruby on rails 销毁回调前的Rspec,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,回调: before_destroy :cannot_destroy_if_has_consent_form def cannot_destroy_if_has_consent_form if self.consent_forms.any? errors.add(:base, 'Language is associated with consent form and cannot be deleted') false end end RSp

回调:

  before_destroy :cannot_destroy_if_has_consent_form

  def cannot_destroy_if_has_consent_form
    if self.consent_forms.any?
      errors.add(:base, 'Language is associated with consent form and cannot be deleted')
      false
    end
  end
RSpec:

 describe "callbacks" do
    it "#cannot_destroy_if_has_consent_form" do
      cl1 = create(:consent_language)
      test_delete(cl1)
      cl2 = create(:consent_language, :active)
      cf = create(:consent_form)
      expect{(test_cannot_delete.cl2).to be_truthy}
    end
  end

如何编写RSpec测试?我开始了,但我不知道如何通过测试,但这是错误的吗?

您必须将同意书孩子连接到同意书语言家长

cf = create(:consent_form, :consent_language => cl2)

否则,关系将不会建立,并且您的
cf
将附加到不同的同意书语言。

不确定您的模型名称和关联,但假设您的
同意书语言
有许多
同意书
并且
同意书
属于
同意书语言

describe "callbacks" do
  it "#cannot_destroy_if_has_consent_form" do
    consent_language = create(:consent_language)
    create(:consent_form, consent_language: consent_language)
    expect { consent_language.destroy }.to_not change(ConsentLanguage, :count)
  end
end

好的,那么应该期望什么呢?test\u cannot\u delete是一个助手方法,你能写出确切的应该是什么样的test吗?test pass:)是的,这些是关联,我认为这很好:)我还有更多的回调要测试,你能帮我吗?感谢这个回调:)作为一个旁注,如果同意表单是一个模型关系,您可以使用关系上的relation
dependent:
选项非常轻松地获得类似的功能,例如:
有很多:同意表单,dependent::restrict\u with\u error
。如果存在子项,这将停止删除父项,并自动向模型中添加一条错误消息。谢谢John:)