2010-08-02 66 views
0

我如何使用Rspec來覆蓋下面的方法?Rspec模型規範

def validate 
    if !self.response.blank? && !self.response.match("<").nil? 
    self.errors.add :base, 'Please ensure that Response field do not contain HTML(<and>) tags' 
    end 
end 

任何人都可以幫忙嗎?

+8

人們會更傾向於幫助你,如果你接受幫助的答案,你以前的問題 - 它是好的,方便的方式來支付社區回來,這也將幫助有類似問題的人爲他們找到解決方案 – Vladimir 2010-08-02 11:24:32

回答

4

從代碼中可以看出,您想要驗證response屬性,並在無效時設置錯誤消息。

因此,假如你的模型被命名爲郵編:

context "HTML tags in response" do 
    before(:each) do 
    @post = Post.new(:response => "<") 
    end 

    it "should not be valid" do 
    @post.should_not be_valid 
    end 

    it "should set the error hash" do 
    @post.errors.should include('Please ensure that Response field do not contain HTML(<and>) tags') 
    end 
end 

您應該檢查的模式,而不是實施方案的期望行爲。驗證是在自定義方法中發生還是在Rails內置的驗證例程中都無關緊要。

作爲一個方面說明,通常最好將錯誤消息添加到屬性而不是errors.base。所以,你可能會說,而不是:

self.errors.add(:response, "etc. etc.")