Why do we use factories for testing?
By: Johnathon Wright on: September 23, 2009
A client recently asked me why we used factories in our tests. Here's my answer:
Originally, people would create a new instance of every model in every test. So, if you were testing that we properly parse dates and know which ones are valid and which aren't, and you know that Person requires a name, you might write:
Person.new(:name => 'fiona', :dob => '3/5/12').should be_valid
and that was cool
validatespresenceof :emailvalidatespresenceof :favorite_color
Person.new(:name => 'fiona', :email => 'firstname.lastname@example.org', :dob => '3/5/12', :favoritecolor => 'red').should bevalid
Person.new(:name => 'fiona', :email => 'email@example.com', :dob => '3/12', :favoritecolor => 'red').shouldnot be_valid
just to make sure we were properly parsing dates and ensuring we got a complete one.
and so that was moderately painful, but then...
we split name into firstname and lastname
and then we have to change 75 tests
so then someone said, "This is really painful."
"Let's create a default Person, and just modify it when we want to test things."
and the solution followed the "GoF pattern called Factory":http://en.wikipedia.org/wiki/Abstractfactorypattern so that's what they called it.