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
# ./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
Another way to define a variable in RSpec is to use the let syntax. The let method should be called inside an example group. The first argument is the name of a variable to define.
The describe Keyword The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.
To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With