I'm trying to create an error with two FactoryGirl models. I have cars and car manufacturers. Cars belong to Car manufacturers so the foreign key/variable belongs in car. When I run my tests, I get this error.
Failure/Error: car = FactoryGirl.build(:car)
NoMethodError:
undefined method `car_manufacturer=' for #<Car:0x0000010437a7d0>
Here are my factories located in spec/factories folder
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
I don't have anything set up in my associations validations because from what I understood, factory girl is seperate so this should work. Perhaps something is wrong in my spec:
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
Thank you for the help. I'm just unsure why this would happen and don't know what I should try to fix it.
Ok, so I think I found the answer. Before I didn't have the associations in my model file. I have since added them below:
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
My new question is, does Factory Girl depend on the model validations? I was under the impression that it didn't. Can someone clarify. I tried the github documentation but I don't remember that it explicitly said so. Thx.
car
andcar_manufacturer
? Please include the declaration ofaccepts_nested_attributes_for
helper as well if there are any. Given the error it might be that you don't haveaccepts_nested_attributes_for
. – vee