我刚刚开始使用FactoryGirls用于Ruby和Rails,我不明白为什么当我尝试运行测试时FactoryGirl给我这个错误:
> Failures:
>
> 1) Staffroom should create a valid staffroom from factory girl
> Failure/Error: staffroom.should be_valid
> NoMethodError:
> undefined method `location' for nil:NilClass
> ./app/models/location.rb:97:in `interpret_location_string'
> ./app/models/location.rb:270:in `find_record_match'
> ./app/models/location.rb:248:in `fetch_and_invalidate_cache_or_create'
> ./app/models/location.rb:83:in `location_lookup'
> ./app/concerns/has_location.rb:21:in `geocode_with_cache'
> ./spec/models/staffroom_spec.rb:52:in `block (2 levels) in <top (required)>'
> -e:1:in `<main>'
这是我在spec / models / staffroom_spec.rb中的代码:
describe Staffroom do
it 'should create a valid staffroom from factory girl' do
staffroom = build_stubbed(:group_staffroom)
staffroom.should be_valid
staffroom = build_stubbed(:industry_staffroom)
staffroom.should be_valid
staffroom = build_stubbed(:company_staffroom)
staffroom.should be_valid
end
end
我在spec / factories / staffrooms.rb中的代码:
FactoryGirl.define do
factory :staffroom do
name { Faker::Company.name }
location 'NEW YORK, NY, 13123'
factory :industry_staffroom do
staffroom_type 'Industry'
end
factory :company_staffroom do
staffroom_type 'Company'
end
end
end
我想我只是对于为什么FactoryGirl会在models / location.rb下查看? 任何帮助将不胜感激。
编辑: 这是location.rb第97行的代码:
94 def self.interpret_location_string(location_string)
95 not_defined_loc = Location.where(city: "SYDNEY*").first
96
97 unless not_defined_loc.location == location_string
感谢。
答案 0 :(得分:0)
Location.interpret_location_string
时会调用 Staffroom
,而第95行的查询似乎没有返回Location
个对象。在访问其属性之前,您应该检查是否有对象。