Rspec before_destroy回调

时间:2017-06-21 19:49:20

标签: 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

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测试?我开始但我不知道如何,总是通过测试,但是错了吗?

2 个答案:

答案 0 :(得分:1)

不确定您的模型名称和关联,但假设您的ConsentLanguage has_many consent_formsConsentForm belongs_to consent_language

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

答案 1 :(得分:0)

您必须将consent_form子级连接到consent_language父级。

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

否则,系统不会设置关系,并且您的cf会附加到其他consent_language。