Last Updated: July 19, 2016
·
3.629K
· jan0sch

Rails, FactoryGirl and has_and_belongs_to_many

When testing hasandbelongstomany models using rspec and factory girl you should setup your factory the following way:

FactoryGirl.define do
  factory :foo do
    name "Foo" 
  end

  factory :bar do
    name "Bar"
    foos { |a| [a.association(:foo)] }
  end
end

This is slightly more verbose than association(:foos, :factory => :foo) but it works without getting errors. ;-)