Rspec Model Specification

How can I use the method below 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

Does anyone help?

0
source share
1 answer

You can see from the code that you want to check the attribute responseand set the error message if it is invalid.

So, if your model is called 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 

You should check the desired model behavior, not the implementation. It doesn’t matter if validation is done in the user method or in the built-in Rails validation routines.

As a note, it is usually better to add an error message to the attribute rather than errors.base. Therefore you can say:

self.errors.add(:response, "etc. etc.")
+4
source

All Articles