do book = Book.new(title: "POODR", subtitle: "An Agile Primer", publication_year: 2012) expect(book.full_title).to eq "POODR: An Agile Primer" end end 4
do book = Book.new(title: "POODR", subtitle: "An Agile Primer", publication_year: 2012) expect(book.full_title).to eq "POODR: An Agile Primer" end end 5
true validates :subtitle, presence: true validates :publication_year, presence: true end describe "#full_title" do it "combines the title and subtitle" do # Invalid book = Book.new(title: "POODR", subtitle: "An Agile Primer") expect(book.full_title).to eq "POODR: An Agile Primer" end end 8
Include all data that impacts expectation • Include no data that doesn't impact expectation # books_factory.rb factory :book do title { "default" } subtitle { "default" } publication_year { 2018 } end # book_spec.rb it "has a publication year" do book = FactoryBot.build_stubbed( :book, title: "POODR", subtitle: "An Agile Primer" ) expect(book.publication_year).to eq 2018 end 9
• Changes to factories have cascading effects • It can be slower than building an object directly # books_factory.rb factory :book do title { "default" } subtitle { "default" } publication_year { 2018 } author end factory :author 10
db? • Do I need associations? • Do I need a lot of data to test this operation? If not, I might not need a factory. describe "#full_title" do it "combines the title and subtitle" do book = Book.new(title: "POODR", subtitle: "An Agile Primer") expect(book.full_title).to eq "POODR: An Agile Primer" end end 12
• build_stubbed • attributes_for # Return an unsaved book instance book = build(:book) # Return a saved book instance book = create(:book) # return an object with all defined attributes stubbed out stub = build_stubbed(:book) # return a hash of attributes that can be used to build a book instance attributes = attributes_for(:book) 13
• build_stubbed • attributes_for # Return an unsaved book instance book = build(:book) # Return a saved book instance book = create(:book) # return an object with all defined attributes stubbed out stub = build_stubbed(:book) # return a hash of attributes that can be used to build a book instance attributes = attributes_for(:book) 14
do name { "Chloe Ardelia Wofford" } pen_name { "Toni Morrison" } after(:create) do |author| create(:book, author: author) end end create(:author).pen_name # Toni Morrison create(:author).book.title # The Bluest Eye 16
do name { "Chloe Ardelia Wofford" } pen_name { "Toni Morrison" } after(:create) do |author| create(:book, author: author) end end create(:author).pen_name # Toni Morrison create(:author).book.title # The Bluest Eye 17