HashFactory
The simplest Rails test factory ever.
Install
braid add git://github.com/brentgreeff/hash_factory.git -p
Add this line to the top of test/test_helper.rb
require 'test_help' # this should already be here
HashFactory.setup
Lets start with the calling code
I like to setup my test data, right there in the test where everyone can see it.
-
Along the lines of
test "A User with a blank last name should be invalid" do @user = create_user :last_name => '' assert @user.invalid? end
A few things to notice:
I don’t call Factory.create_user. All that ‘Factory’ typing just adds noise and makes my fingers sore.
I define the arguments relevant to the test explicitly. I dont need to look at the implementation to see if the user has a last_name.
I assume the factory handles the rest and passes me a ‘VALID’ instance.
Test things in isolation
A factory that returns an invalid instance will eventually cause a failure that ripples through your test code. Face slapping will ensue.
How does it work?
-
create a factories directory:
mkdir test/factories
Add a module to this folder and the methods automatically become available in your tests.
-
Mine tend to look like this:
module UserFactory def create_user(={}) build :user, () end def (={}) { :first_name => 'Jim', :last_name => 'Bean', :email => "[email protected]", :account => [:account] || create_account }.merge() end end
Add as many or as few files as you like.
The advantage of using this plugin is you can build your objects any way you like.
Don’t worry about protected attributes the ‘build’ method handles it for you.
Pluralization Issues
Be sure to update your ‘initializers/inflections.rb’ If you get an Constant missing error when loading a factory.
Factory love in the console.
Call
require 'hash_factory'
HashFactory.load_in(self)
Or event better
copy the file:
config/initializers/factory_in_console.rb
and it’s always there waiting for you.
Copyright © 2009 [Brent Greeff], released under the MIT license