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 "firstname.lastname@example.org" 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. =)
Reference: thoughtbot / factory_girl_rails
One thought on “Rails – Create Mock Data for RSpec”