Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl definition - undefined method for association

I have the following

in /app/models:

class Area < ActiveRecord::Base
   has_many :locations
end
class Location < ActiveRecord::Base
   belongs_to :area
end

in /app/test/factories/areas.rb

FactoryGirl.define do
  factory :area do
    name 'Greater Chicago Area'
    short_name 'Chicago'
    latitude 42
    longitude -88
  end
  factory :losangeles, class: Area do
     name 'Los_Angeles Area'
     short_name 'Los Angeles'
     latitude 50
     longitude 90
  end
end

in /app/test/factories/locations.rb

FactoryGirl.define do
  factory :location do
    name "Oak Lawn"
    latitude 34
    longitude 35
    association :area
  end
  factory :malibu, class: Location do
    name "Malibu"
    latitude 60
    longitude -40
    association :losangeles
  end
end

When I try to run this I get:

NoMethodError: undefined method `losangeles=' for #<Location:0x00000102de1478>
test/unit/venue_test.rb:10:in `block in <class:VenueTest>'

Any help appreciated.

like image 458
Mark Fraser Avatar asked Nov 01 '12 15:11

Mark Fraser


1 Answers

You're getting this error because you're trying to say to your malibu factory to set an association called losangeles, which doesn't exist. What exists is the factory losangeles which creates an Area. What you want is:

FactoryGirl.define do
  factory :location do
    name "Oak Lawn"
    latitude 34
    longitude 35
    association :area
  end
  factory :malibu, class: Location do
    name "Malibu"
    latitude 60
    longitude -40
    association :area, factory: :losangeles
  end
end

See documentation here

Note that you could also use nesting to define the second factory:

FactoryGirl.define do
  factory :location do
    name "Oak Lawn"
    latitude 34
    longitude 35
    association :area

    factory :malibu do
      name "Malibu"
      latitude 60
      longitude -40
      association :area, factory: :losangeles
    end

  end
end
like image 172
pjam Avatar answered Nov 14 '22 19:11

pjam