Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Testing 101: A night out with factory girl

Testing 101: A night out with factory girl

Going over factory girl basics and some of the more advanced features

Bradley Temple

July 15, 2013
Tweet

Other Decks in Programming

Transcript

  1. Basic Factories factory :user do username “Bob” age 30 end

    “Snapshot” of object data that’s reusable in tests
  2. Basic Factories Associations factory :post do title “Hi!” body “Hello!”

    user end Makes an object of the factory named the same thing
  3. Basic Factories Sequences factory :user do sequence(:username) { |n| “user#{n}”

    } age 30 end Automatically increments the attribute to take care of uniqueness constraints
  4. Basic Factories Attribute blocks factory :user do sequence(:username) { |n|

    “user#{n}” } age 30 password “secret” password_confirmation { |u| u.password } end
  5. Basic Factories Child Factories factory :user do sequence(:username) { |n|

    “user#{n}” } admin false factory :admin do admin true end end
  6. Stay outta the database! build_stubbed(:admin) Creates mock object based on

    attributes defined in the factory Will throw an exception if your test attempts to interact with the database at all
  7. Named Associations class Message < ActiveRecord::Base belongs_to :sender, class_name: “User”,

    foreign_key: “sender_id” belongs_to :recipient, class_name: “User”, foreign_key: “recipient_id” end
  8. Traits factory :user do username “Bob” age 30 trait :voting_age

    do age 18 end trait :drinking_age do age 21 end end
  9. Using Traits drinking_buddy = create(:user, :drinking_age) Method One: Called Directly

    Method Two: Child Factory factory :user do username “Bob” age 30 trait :drinking_age do age 21 end factory :drinking_buddy, :traits => [:drinking_age] end
  10. Combining Traits factory :user do username “Bob” age 30 trait

    :drinking_age do age 21 end trait :admin do admin true end factory :go_home_admin_your_drunk, :traits => [:drinking_age, :admin] end This is like factory multiple inheritance
  11. Ignored Attributes & Callbacks factory :user do sequence(:username) { |n|

    “user#{n}” } age 30 factory :user_with_posts do ignore do post_count 1 end after(:create) do |user, factory| create_list :post, factory.post_count, user: user end end end
  12. Plain old ruby objects factory :url, class: String do skip_create

    protocol “http://” host “www.google.com” port 80 trait :secure do protocol “https://” end initialize_with { new(“#{protocol} #{host}:#{port}”) } end