Rails 3 with RSpec and Factory_Girl

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:

The setup:

  • rails 3.0.10
  • devise 1.1.rc0
  • capybara
  • rspec-rails
  • 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:

spec/factories.rb

spec/factories/*.rb

And we can add the following code in the files:

include ActionDispatch::TestProcess
FactoryGirl.define do
  factory :admin, :class => User do
    email "your@mail.com"
    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
    before(:each) do
      user = FactoryGirl.create(:admin)
      visit("/users/login")
      fill_in('Email', :with => user.email)
      fill_in('Password', :with => user.password)
      click_button('Sign in')
    end
    it "should fill in the form" do
      visit("/homepage")
      fill_in "firstname", :with => "hello"
      fill_in "lastname", :with => "world"
      click_button "submit"
    end
  end

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!

Ref.

thoughtbot/factory_girl

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s