Ruby on rails FactoryGirl外键空白
我的产品模型有外键约束,我正试图使用Rspec和FactoryGirl对此进行测试,但是当我尝试这样做时,我不断得到以下错误:Ruby on rails FactoryGirl外键空白,ruby-on-rails,ruby,rspec,factory-bot,Ruby On Rails,Ruby,Rspec,Factory Bot,我的产品模型有外键约束,我正试图使用Rspec和FactoryGirl对此进行测试,但是当我尝试这样做时,我不断得到以下错误: Failure/Error: @product = FactoryGirl.create(:product) ActiveRecord::RecordInvalid: Validation failed: Products category can't be blank, Products department can't be blank 工厂 F
Failure/Error: @product = FactoryGirl.create(:product)
ActiveRecord::RecordInvalid:
Validation failed: Products category can't be blank, Products department can't be blank
工厂
FactoryGirl.define do
factory :category do
category_name "Trousers"
slug "trousers"
products_attributes { [ FactoryGirl.attributes_for(:product) ]}
end
factory :department do
department_name "mens"
slug "mens"
end
factory :product do
sequence(:name) {|n| "Foo#{n}" }
price 9999
description "I am a foobar"
slug "foo"
image Rails.root.join("spec/fixtures/images/boom.jpg").open
department
category
end
产品模型
class Product < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
has_attached_file :image
attr_accessible :ranges, :name, :price, :description, :category_id, :slug, :image, :image_file_name, :department_id, :sizings_attributes
attr_accessor :ranges
belongs_to :category
belongs_to :department
has_many :sizings, :dependent => :destroy
has_many :sizes, :through => :sizings
has_many :basket_items
before_save :downcase_name
validates_presence_of :price
validates :price, :numericality => true
validates_presence_of :name
validates_uniqueness_of :name
validates_presence_of :description
validates_attachment_presence :image
validates :category_id, :presence => true
validates :department_id, :presence => true
您的
部门
和类别
模型是否正在验证您是否尝试使用FactoryGirl
而不是通过关联创建它们?是的,它们是在其他规范中创建的。请尝试删除产品属性{[FactoryGirl.attributes\u for(:product)]}
行。首先,为什么要有这条线?删除它有效吗?如果通过产品工厂创建类别本身,我不明白为什么需要嵌套属性。如果您在其他测试中使用属性,那么请尝试使用。是的,删除它是有效的,因为它不再使用,所以不需要在那里。
feature 'Product' do
context "when logged in" do
before(:each) do
@product = FactoryGirl.create(:product)
@user = FactoryGirl.create(:user)
@size = FactoryGirl.create(:size)
@sizing = FactoryGirl.create(:sizing)
visit new_user_session_path
fill_in "Email", :with => @user.email
fill_in "Password", :with => @user.password
click_button "Sign in"
page.should have_content("Signed in successfully.")
end
scenario "creation" do
visit '/admin/products/new'
fill_in "Name", :with => "Foo"
fill_in "Description", :with => "Baz"
fill_in "Price", :with => 1000
attach_file "Image", Rails.root.join('spec', 'fixtures', 'images', 'boom.jpg')
find(:xpath, "//option[1]", :match => :first ).click
fill_in "product_sizings_attributes_0_quantity", :with => 10
click_button "Create Product"
page.has_xpath?("/html/body/div[2]/p")
end