Why do we use factories for testing?
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:
and that was cool
then eventually:
then
and
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 first_name and last_name
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 so that's what they called it.
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:
1 |
Person.new(:name => 'fiona', :dob => '3/5/12').should be_valid |
then eventually:
1 |
validates_presence_of :emailvalidates_presence_of :favorite_color |
1 |
Person.new(:name => 'fiona', :email => 'fiona@gmail.com', :dob => '3/5/12', :favorite_color => 'red').should be_valid |
1 |
Person.new(:name => 'fiona', :email => 'fiona@gmail.com', :dob => '3/12', :favorite_color => 'red').should_not be_valid |
and so that was moderately painful, but then...
we split name into first_name and last_name
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 so that's what they called it.