简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM