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的测试?我开始了,但我不知道如何,总是通过测试,但它是错的?
正如一个侧面说明,如果consent_forms是模特的关系,你可以很轻松地得到类似的功能使用关系上的'dependent:'选项,就像这样:'has_many:consent_forms,dependent :::restrict_with_error'。如果存在孩子,这将停止父母的删除,并自动向您的模型添加错误消息。 –
谢谢John! :) – VladimirR