Rails RSpec (beginner): Why is this test sometimes passing and sometimes not?

Viewed 13

I have a book database where books can have different book formats (hardcover, softcover etc).

I have factories with factory_bot.

The following spec just run through with an error - and then when I run it the second time, it worked. I have no idea where I need to start searching....

The error was:

  1) BookFormat displays the proper book format for a book with that format
     Failure/Error: expect(@book.book_format.name).to eq('Hardcover')
     
       expected: "Hardcover"
            got: "Not defined"

Here is the full spec:

require 'rails_helper'

RSpec.describe BookFormat, type: :model do
  before(:all) do
    @book = create(:hobbit)
    @book_format_default = create(:not_defined)
  end

  it 'displays the proper book format for a book with that format' do
    expect(@book.book_format.name).to eq('Hardcover')
  end

  it 'should reassign to the fallback book_format if their book_format is deleted' do
    format = @book.book_format
    format.destroy
    expect(@book.reload.book_format.id).to eq(@book_format_default.id)
  end

  it 'should not let the fallback format be deleted' do
    format = @book_format_default
    format.destroy
    expect(format).to be_truthy
  end

end

Here is the corresponding factor for the book :hobbit:

  factory :hobbit, class: Book do
    title { 'The Hobbit' }
    year { 1937 }
    rating { 5 }
    condition { 4 }
    synopsis {  "<p>#{Faker::Lorem.paragraphs(number: 30).join(' ')}</p>" }
    association :book_format, factory: :hardcover
    association :user, factory: :me
    genres { [ create(:fiction) ] }

    after(:build) do |hobbit|
      hobbit.cover.attach(
        # rubocop:disable Rails/FilePath
        io: File.open(Rails.root.join('db', 'sample', 'images', 'cover-1.jpg')),
        # rubocop:enable Rails/FilePath
        filename: 'cover.jpg',
        content_type: 'image/jpeg'
      )
    end
  end

And here are the factories for book_formats:

FactoryBot.define do
  factory :not_defined, class: BookFormat  do
    name { 'Not defined'}
    fallback { true }
  end
  factory :hardcover, class: BookFormat do
    name { 'Hardcover' }
  end

  factory :softcover, class: BookFormat do
    name { 'Softcover' }
  end
end
0 Answers
Related