1
votes

This is my test for validation, i would like to find the best way to writing model specs, especially for validation. But I have problem with this code below.

require 'spec_helper'

describe Ad, :focus do
  let(:ad) { Ad.sham!(:build) }

  specify { ad.should be_valid }

  it "not creates a new instane given a invalid attribute" do
    ad = Ad.new
    ad.should_not be_valid
  end

  [:title, :category_id, :email, :ad_content, :name, :price].each do |attr|
    it "should require a #{attr}" do
      subject.errors[attr].should include("blank") 
    end
  end    
end

When I run this spec i receive this error:

   5) Ad should require a name
     Failure/Error: subject.errors[attr].should include("blank")
       expected [] to include "blank"
       Diff:
       @@ -1,2 +1,2 @@
       -blank
       +[]
     # ./spec/model/ad_spec.rb:15:in `block (3 levels) in <top (required)>'
1

1 Answers

4
votes

The problem here is that you're not calling valid? in that example before checking for errors. You're calling it (indirectly) in the previous example, but not the one that you're asserting that has errors.

The correct way is this:

[:title, :category_id, :email, :ad_content, :name, :price].each do |attr|
  it "should require a #{attr}" do
    subject.valid?
    subject.errors[attr].should include("blank")
  end
 end