Rails – Create Mock Data for RSpec

When running the test cases, most likely we need some mock data to test the functionality of our code. The factory_girl_rails gem is useful for creating mock data for testing purpose.

1. Include the factory_girl_rails in Gemfile

group :test do
  gem 'rspec', '2.2.0'
  gem 'webrat', '0.7.1'
  gem 'factory_girl_rails', '1.0'
end

 

2. Install the newly added gem

  • bundle install

 

3. Create the <rails_project_root>/spec/factories.rb

Factory.define :user do |user|
  user.username              "Yuen Ying Kit"
  user.email                 "yingkityuen@gmail.com"
  user.password              "password"
  user.password_confirmation "password"
end

 

4. You can now create the above user in the RSpec test

describe "for an authorized user" do

  before(:each) do
    # Create the user object by factory
    @user = Factory(:user)
    # Sign in the yser
    test_sign_in(@user)
  end
...

 

The factory_girl_rails gem could help you creating sequences of data. Let me show you how to do it later. =)

Done =)

Reference: thoughtbot / factory_girl_rails

About these ads

One thought on “Rails – Create Mock Data for RSpec”

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