Home > Software design >  Rspec-Rails: How to create an active record collection with a faker factory?
Rspec-Rails: How to create an active record collection with a faker factory?

Time:08-11

I am trying to learn Rspec and I fail with testing a view that is expecting an Active Record collection (a simple index view). I need a variable @books (which would usually contain Book.all), which shall be created with factory bot and faker.

This here doesn't seem to work - as this doesn't give back an Active Record collection, but rather a normal array of objects.

@books = Array.new(3) { create(:random_book) }

My Faker factory setup for :random_book:

FactoryBot.define do
  factory :random_book, class: Book do
    title { Faker::Book.title }
    year { Random.rand(1920..2020) }
    rating { Random.rand(0..5) }
    condition { Random.rand(0..5) }
    association :book_format, factory: :not_defined
  end
end

Thanks for any help. I did read the "view spec" part of the RSpec doc but I don't get what they are doing there - the code that is there ALSO seems to create a simple array?

CodePudding user response:

Yes, you are creating an array. If you want an ActiveRecord collection, then something like this might work:

3.times{ FactoryBot.create(:random_book) }
@books = Book.all
  • Related