Using Factories

Let's also test that our factories work..

Now let's create a factory for cats to learn how to user FactoryBot and Faker for test data...

Open spec/factories/cats.rb and change the name, breed, and bio to use Faker data.

FactoryBot.define do
  factory :cat do
    name   { Faker::Cat.name } 
    bio    { Faker::RickAndMorty.quote }

    # Notice the difference between the { } fields and the below
    # Generate a few instances of your factory in rails console
    # to see if you can understand the difference
    breed  Faker::Cat.breed
  end
end

Factories can also have traits. Let's say we want to have an easy way to make a "Suphalak" breed of cat...

FactoryBot.define do  
  factory :cat do
    ...

    trait :suphalak do
      breed "Suphalak"
    end
  end
end

You could then create a Suphalak cat with FactoryBot.create(:cat, :suphalak)

Let's test that out.

  • Make a Factory in console -- does it work?
  • Add a test to your model -- that it has a valid Factory
  • Make it pass

Remember: your tests are just untested code!

results matching ""

    No results matching ""