我试图用两个FactoryGirl模型创建错误。我有汽车和汽车制造商。汽车属于汽车制造商,因此外键/变量属于汽车。当我运行测试时,我收到此错误。
Failure/Error: car = FactoryGirl.build(:car)
NoMethodError:
undefined method `car_manufacturer=' for #<Car:0x0000010437a7d0>
以下是我的工厂位于spec / factories文件夹
FactoryGirl.define do
factory :car do
color 'Black'
year 2012
mileage 50000
description 'Badass used car'
car_manufacturer
end
end
FactoryGirl.define do
factory :car_manufacturer do
name 'Speed Racer Inc.'
country 'Japan'
end
end
我没有在我的协会验证中设置任何东西,因为根据我的理解,工厂女孩是分开的,所以这应该工作。也许我的规范出了点问题:
scenario 'I want to associate a car with a car manufacturer' do
car_manufacturer = FactoryGirl.create(:car_manufacturer)
car = FactoryGirl.build(:car)
car_count = Car.count
visit new_car_path
fill_in 'Color', with: car.color
select car.year, from: 'Year'
fill_in 'Mileage', with: car.mileage
fill_in 'Description', with: car.description
select car_manufacturer.name, from: 'Owner'
click_on 'Create Car'
expect(page).to have_content('Car Submitted')
expect(Car.count).to eql(car_count + 1)
end
感谢您的帮助。我不确定为什么会发生这种情况,也不知道应该尝试解决这个问题。
好的,所以我觉得我找到了答案。在我的模型文件中没有关联之前。我已经在下面添加了它们:
require 'spec_helper'
describe Car do
it { should validate_presence_of(:color) }
it { should validate_presence_of(:year) }
it { should validate_presence_of(:mileage) }
it { should ensure_inclusion_of(:year).in_array(Car::YEARS) }
it { should_not have_valid(:year).when('','nineteenninetynine',1979) }
it { should_not have_valid(:mileage).when('3300 miles') }
it { should belong_to(:car_manufacturer) }
end
require 'spec_helper'
describe CarManufacturer do
it { should validate_presence_of(:name) }
it { should validate_presence_of(:country) }
it { should_not have_valid(:name).when('',nil) }
it { should_not have_valid(:country).when('',nil) }
it { should have_many(:cars) }
end
我的新问题是,Factory Girl是否依赖模型验证?我的印象是它没有。有人可以澄清一下。我尝试了github文档,但我不记得它明确这么说。 THX。
答案 0 :(得分:2)
您是否可以验证是否已迁移测试数据库?通常,当访问者无法正常工作时(在此示例中为car_manufacturer=
),它拼写错误或测试数据库未正确迁移(因为AR会在桌面上活动)。