2017-06-21 44 views
0

回调:Rspec的before_destroy回调

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

+0

正如一个侧面说明,如果consent_forms是模特的关系,你可以很轻松地得到类似的功能使用关系上的'dependent:'选项,就像这样:'has_many:consent_forms,dependent :::restrict_with_error'。如果存在孩子,这将停止父母的删除,并自动向您的模型添加错误消息。 –

+0

谢谢John! :) – VladimirR

回答

0

不确定您的型号名称和协会,但假设你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 
+0

测试通:)是的,那些是我认为这是好的协会:) – VladimirR

+0

我有更多的回调测试,你能帮我吗?感谢这个回调:) – VladimirR

0

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

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

否则,关系不成立,并且您cf被连接到不同的consent_language。

+0

好的,应该在期望什么?test_cannot_delete是一个辅助方法 你能写出准确的应该看起来像测试吗? – VladimirR