Skip to content

Instantly share code, notes, and snippets.

@jennli
Last active February 18, 2016 17:25
Show Gist options
  • Save jennli/d0b97c467b1e48e4e723 to your computer and use it in GitHub Desktop.
Save jennli/d0b97c467b1e48e4e723 to your computer and use it in GitHub Desktop.
  • to ensure migration runs for test environment
rake db:migrate RAILS_ENV=test

or

fundsy $ bin/rake db:test:prepare

Factory Girl

FactoryGirl.define do
  factory :user do
    first_name {Faker::Name.first_name}
    last_name {Faker::Name.last_name}
    sequence(:email) {|n| "#{n}-#{Faker::Internet.email}"}
    password {Faker::Internet.password}
  end
end
  • generates a set of attributes
FactoryGirl.attributes_for(:user)
  • builds a record and save it in memory instead of in database
FactoryGirl.build(:user)
  • build a record and save it in database
FactoryGirl.create(:user)
  • override the FactoryGirl create/build with customized parameters:
u = FactoryGirl.build(:user, {last_name: nil})
  • create pledge

support

  • create a helper module in spec/support folder called LoginHelpers
  • uncomment out the following from rails_helper.rb
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
  • add the following in the same file:
config.include LoginHelpers
  • implement the helper method in the LoginHelpers module
module LoginHelpers
  def signin(user)
    request.session[:user_id] = user.id
  end
end
  • then use the helper method in the helper module
signin(user)
  • automatically associate child to a new parent if don't specify a parent
FactoryGirl.define do
  factory :pledge do
    # this will automatically create a campaign record and associate the pledge
    # record with it, if you don't pass a campaign to the pledge factory
     association :campaign, factory: :campaign
     association :user, factory: :user
    amount {1 + rand(1000)}
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment