After begun to write the test code in Ruby on Rails with RSpec, but it doesn’t run smoothly as I have encountered several problems. Such as the sign_in method in devise, though it is written in the site, but it doesn’t work in my situation. And I would like to test the user visits my homepage with authentication, I have detailed all the processes which include the fixture. So I decide to use factory_girl.
Quoting from github:
factory_girl is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance.
So… Let’s begin:
- rails 3.0.10
- devise 1.1.rc0
- factory_girl_rails ~> 1.1 (for rails)
I think it is enough for the gem, and I have already installed rspec, so I just add the last line in the gemfile and do bundle install in the terminal.
Then we have to add the factory into the spec. There are two ways to do that:
And we can add the following code in the files:
include ActionDispatch::TestProcess FactoryGirl.define do factory :admin, :class => User do email "firstname.lastname@example.org" password "helloworld" password_confirmation "helloworld" end end
Ok, we have registered a factory girl, and we could use it like this:
describe "when visiting homepage with authentication" do
user = FactoryGirl.create(:admin)
fill_in('Email', :with => user.email)
fill_in('Password', :with => user.password)
it "should fill in the form" do
fill_in "firstname", :with => "hello"
fill_in "lastname", :with => "world"
The factory_girl supports several different build strategies:
# Returns a User instance that’s not saved
user = FactoryGirl.build(:user)
# Returns a saved User instance
user = FactoryGirl.create(:user)
# Returns a hash of attributes that can be used to build a User instance
attrs = FactoryGirl.attributes_for(:user)
# Returns an object with all defined attributes stubbed out
stub = FactoryGirl.stub(:user)
That’s cool, doesn’t it!