bulleric
bulleric

Reputation: 2127

Rspec: How can i test an optional field

Currently i am learning with the youtube video Efficient Rails Test Driven Development - by Wolfram Arnold One exercise is:

A Person object has an optional middle_name.

I create a migration to add the middle name to the database

and i write a spec

it "can have a middle name"

But i got no idea how to test this issue how can i test an optional field

thanks for help

Bulleric

Upvotes: 1

Views: 997

Answers (2)

zetetic
zetetic

Reputation: 47548

To say that an attribute is 'optional' implies that the instance is valid when the attribute is nil. So:

it "does not require a middle name" do
  @person = Person.new
  @person.valid?
  @person.errors[:middle_name].should_not include("can't be blank")
end

If you're using shoulda then this can be made even simpler:

describe Person do
  it { should_not validate_presence_of(:middle_name) }
end

Upvotes: 1

Jatin Ganhotra
Jatin Ganhotra

Reputation: 7015

Assuming you are using Factor_girl, create two factories,

person1 = Factory.create(:person, :first_name=> "A")  
person2 = Factory.create(:person, :first_name=> "A", :middle_name => "M")

Now, in your test, show that person1 and person2 both get saved to the database.
You could do the same with fixtures, if you are not using factory_girl.

Upvotes: 0

Related Questions