How to write rspec for an empty field? [Rails3.1]

I use rails 3.1 + rspec and factory girl.

My field validation (validates_presence_of) works. How to get a test to use this fact as “success” rather than “failure”
Specification:

describe "Add an industry with no name" do
  context "Unable to create a record when the name is blank" do
    subject do
      ind = Factory.create(:industry_name_blank)
    end
    it { should be_invalid }
  end
end

but I get a failure:

Failures:

  1) Add an industry with no name Unable to create a record when the name is blank 
     Failure/Error: ind = Factory.create(:industry_name_blank)
     ActiveRecord::RecordInvalid:
       Validation failed: Name can't be blank
     # ./spec/models/industry_spec.rb:45:in `block (3 levels) in <top (required)>'
     # ./spec/models/industry_spec.rb:47:in `block (3 levels) in <top (required)>'

Finished in 0.20855 seconds
8 examples, 1 failure

Model Code:

class Industry < ActiveRecord::Base
  validates_presence_of :name
  validates_uniqueness_of :name
end

Factory Code:

Factory.define :industry_name_blank, :class => 'industry' do |industry|
  industry.name   { nil }
end
+5
source share
2 answers

Here is an example ... the subject is filled in "Industry.new" by agreement

describe Industry do

  it "should have an error on name when blank" do
    subject.name.should be_blank
    subject.valid?
    subject.should have(1).error_on(:name)
    #subject.errors.on(:name).should == "is required"
  end

end

The latter is a little fragile, but you can do it

More syntax details: http://cheat.errtheblog.com/s/rspec/

+8
source

Factory.build(:industry_name_blank) , Factory.create(:industry_name_blank) . , - name, .

create build, : Factory.build(:industry_name_blank). , :

subject.should_not be_valid
subject.should have(1).error_on(:name)
+2

All Articles