Rspec 型号规格 [英] Rspec model spec
问题描述
我如何使用 Rspec 覆盖以下方法?
How do i cover the below method using 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
有人可以帮忙吗?
推荐答案
从代码看来,您想要的是验证 response
属性并在无效时设置错误消息.
It appears from the code that what you want is to validate the response
attribute and set an error message if invalid.
假设您的模型名为 Post:
So assuming your model is named 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 内置验证例程中进行,这无关紧要.
You should check for the desired behavior of the model, not the implementation. It shouldn't matter whether the validation is happening in a custom method, or in Rails built-in validation routines.
作为旁注,通常最好将错误消息添加到属性而不是 errors.base
.所以你可能会说:
As a side note, it's generally better to add the error message to the attribute rather than errors.base
. So you might say instead:
self.errors.add(:response, "etc. etc.")
这篇关于Rspec 型号规格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!