Eric Norcross
Eric Norcross

Reputation: 4306

Fabrication has_many though with validation

I'm just getting into testing and I have many models that utilize a has_many though relationship. In each case, one model requires that the other be present at the time of save. I've run into a wall with every testing system I've tried (FactoryGirl, Fixtures, and now Fabrication) where I can not figure out how to set up the tests correctly to replicate this behavior.

I followed this GIST as an example but changed the after_build to before_save as the models are requiring the "though" model at that time. Am I approaching this the wrong way? How does one test this relationship/functionality?

I've created a GIST that is hopefully easier to use/read.

Upvotes: 1

Views: 1180

Answers (1)

Eric Norcross
Eric Norcross

Reputation: 4306

I changed this

Fabricator(:brand) do
  title "Coca Cola"

  before_save do |brand|
    styles Fabricate(:brand_style, :brand => brand, :style => Fabricate(:style))
  end
end

to this

Fabricator(:brand) do
  title "Coca Cola"

  styles(count: 3) { Fabricate(:style) }
end

and now the test is passing. However, I'm not sure if this is the correct way of setting this up, so if anyone has any additional insight it would be appreciated.

Upvotes: 3

Related Questions