FactoryBot Dynamic Attributes
Asked Answered
S

1

5

In the 5.0 FactoryBot release, static attributes will be deprecated and dynamic attributes will have to be used instead. So:

factory :product do
  name 'Some Product'
end

Will need to become:

factory :product do
  name { 'Some Product' }
end

However, in my code, I simplified the assignment of attributes that have the same name but increment a count using a loop:

factory :product do    
  (1..6).each do |n|
    send "image_#{n}", "test_image.jpeg"
  end
end 

Essentially, in my Product model, I have 6 images (image_1, image_2, etc.). In the above code I loop through each and assign "test_image.jpeg" to each. How can I do this using dynamic attributes?

Swinish answered 28/2, 2019 at 2:7 Comment(0)
R
6

Pretty much the same way. Just specify a block after calling send:

factory :product do    
  (1..6).each do |n|
    send("image_#{n}") { "test_image.jpeg" }
  end
end
Rye answered 28/2, 2019 at 2:22 Comment(2)
That's what I did initially but I left out the parentheses, and without the parentheses I get an error so I thought it was something else :|. Thanks!Swinish
Without parentheses, Ruby does not interpret the braces as a block passed to sendCornhusk

© 2022 - 2024 — McMap. All rights reserved.