Skip to content
This repository has been archived by the owner on Mar 30, 2018. It is now read-only.

Latest commit

 

History

History
52 lines (40 loc) · 1.44 KB

03_factories.md

File metadata and controls

52 lines (40 loc) · 1.44 KB

What is a factory?

It's how we set up data in the database for a test

IMPORTANT: Each test should be isolated, which means we need to clean the database between each test

ALSO IMPORTANT: You should only use factories if you need to, for example to pass validations on that class.

So what does one look like?

Well that depends, but we use FactoryBot (formerly FactoryGirl) so it looks like this:

# spec/factories/user.rb
FactoryBot.define do
  factory :user do
    # Notice how there's nothing here. This is intentional.
    # The factory should only have the minimum required default values to allow the class to save.
    # Any additional attributes should be declared by your test or through traits.
    # This forces factories to be a la carte.
  end
end

# spec/test_spec.rb
describe 'User' do
  before do
    create(:user, first_name: 'Tester')
  end

  it 'works correctly' do
    expect(user.first_name).to eq 'Tester'
  end
end

Great! Now let's get into some request specs

Clone the Test API, checkout the learn_rspec branch, and run rake db:setup

Note: This repo already has a few helpers set up to get us writing tests faster, we can revisit these once we get our own tests working

Next Steps