How to write rspec for blank field? [Rails3.1]
I use rails 3.1 + rspec and factory girl.
My validation of required field (validates_presence_of) is working. How do I get the test to use that fact as a 'success' rather than a 'failure'
The spec is: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
# ./s开发者_StackOverflowpec/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
Here's an example... subject gets populated with "Industry.new" by convention
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 last is a little more brittle, but you could do it
More on the syntax: http://cheat.errtheblog.com/s/rspec/
Factory.build(:industry_name_blank)
generates the object while Factory.create(:industry_name_blank)
generates and saves the created object. In your case it can't save the object, because it is invalid due to lacking name
, which is why you get the validation error.
So instead of using create
use build
to avoid hitting the validation errors: Factory.build(:industry_name_blank)
. Then you should be able to spec it out like Jesse suggests:
subject.should_not be_valid
subject.should have(1).error_on(:name)
精彩评论