#158 Factories not Fixtures
Fixtures are external dependencies which can make tests brittle and difficult to read. In this episode I show a better alternative using factories to generate the needed records.
- Download:
- source codeProject Files in Zip (118 KB)
- mp4Full Size H.264 Video (20 MB)
- m4vSmaller H.264 Video (13.2 MB)
- webmFull Size VP8 Video (36.5 MB)
- ogvFull Size Theora Video (27.1 MB)
There is a newer version of this episode, see the revised episode.
Resources
- Factory Girl
- Factory Girl Documentation
- Machinist
- Object Daddy
- Episode 60: Testing Without Fixtures
- Full Episode Source Code
bash
sudo rake gems:install RAILS_ENV=test
sudo rake gems:install RAILS_ENV=test
config/environments/test.rb
config.gem "thoughtbot-factory_girl", :lib => "factory_girl", :source => "http://gems.github.com"
config.gem "thoughtbot-factory_girl", :lib => "factory_girl", :source => "http://gems.github.com"
spec_helper.rb
require File.dirname(__FILE__) + "/factories"
require File.dirname(__FILE__) + "/factories"
spec/factories.rb
Factory.define :user do |f|
f.sequence(:username) { |n| "foo#{n}" }
f.password "foobar"
f.password_confirmation { |u| u.password }
f.sequence(:email) { |n| "foo#{n}@example.com" }
end
Factory.define :article do |f|
f.name "Foo"
f.association :user
end
Factory.define :user do |f| f.sequence(:username) { |n| "foo#{n}" } f.password "foobar" f.password_confirmation { |u| u.password } f.sequence(:email) { |n| "foo#{n}@example.com" } end Factory.define :article do |f| f.name "Foo" f.association :user end
user_spec.rb
describe User do
it "should authenticate with matching username and password" do
user = Factory(:user, :username => 'frank', :password => 'secret')
User.authenticate('frank', 'secret').should == user
end
it "should not authenticate with incorrect password" do
user = Factory(:user, :username => 'frank', :password => 'secret')
User.authenticate('frank', 'incorrect').should be_nil
end
end
describe User do it "should authenticate with matching username and password" do user = Factory(:user, :username => 'frank', :password => 'secret') User.authenticate('frank', 'secret').should == user end it "should not authenticate with incorrect password" do user = Factory(:user, :username => 'frank', :password => 'secret') User.authenticate('frank', 'incorrect').should be_nil end end

