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() tags' end end
有人可以帮忙吗?
从代码中可以看出,您需要的是validationresponse
属性并在无效时设置错误消息。
假设您的模型名为Post:
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内置validation例程中进行validation都无关紧要。
作为旁注,通常最好将错误消息添加到属性而不是errors.base
。 所以你可能会说:
self.errors.add(:response, "etc. etc.")