简体   繁体   中英

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.

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

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