FactoryGirl外键空白

时间:2013-10-27 17:30:34

标签: 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

工厂

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

产品规格

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

0 个答案:

没有答案