Rspec型号规格

时间:2010-08-02 11:20:37

标签: ruby-on-rails 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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:4)

从代码中可以看出,您需要的是验证response属性并设置错误消息(如果无效)。

假设您的模型名为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内置验证例程中进行验证都无关紧要。

作为旁注,通常最好将错误消息添加到属性而不是errors.base。所以你可能会说:

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