如何在Factory Girl中设置此关联

时间:2014-09-10 19:25:11

标签: ruby-on-rails rspec factory-bot

第一次做测试/使用Factory Girl,我很困惑。我有一个名为Partnerships的模型,它与另一个名为Schools的模型有一个has_one关系。

合作模式:

class Partnership < ActiveRecord::Base 
  has_one :school
end

学校模式:

class School < ActiveRecord::Base
   attr_accessible :name
   belongs_to :partnership
end

学校工厂:

FactoryGirl.define do
  factory :school do
    name "Elementary School" 
  end
end

合伙工厂:

FactoryGirl.define do
  factory :partnership do
    association :school

    factory :partnership_for_school do 
        after(:create) do |partnership|
            partnership.school FactoryGirl.build(:school)
        end
    end


  end

end

在我的spec文件中,我尝试创建一个非常简单的测试:

describe "Partnerships" do

    it "should be able to create a partnership with a school" do
        school_partnership = FactoryGirl.create(:partnership_for_school)
        school_partnership.school_id.should_not be_nil
    end



end

但是当我运行这个测试时,我一直认为伙伴关系对象中的school_id是零。我以为我在合伙工厂建立了学校协会,但我在某个地方出错了。

关于我哪里出错的任何想法?

更新

这是运行测试时的堆栈跟踪:

Partnerships should be able to create a partnership with a school
 Failure/Error: school_partnership = FactoryGirl.create(:partnership_for_school)
 ActiveRecord::StatementInvalid:
   PG::UndefinedColumn: ERROR:  column schools.partnership_id does not exist
   LINE 1: SELECT  "schools".* FROM "schools"  WHERE "schools"."partner...
                                                     ^
   : SELECT  "schools".* FROM "schools"  WHERE "schools"."partnership_id" = 17 LIMIT 1
 # ./spec/factories/partnerships.rb:11:in `block (4 levels) in <top (required)>'
 # ./spec/requests/partnerships_spec.rb:8:in `block (2 levels) in <top (required)>'
 # -e:1:in `<main>'

更新2

当我运行rake db:test:prepare时,我收到此错误:

 ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  zero-length delimited identifier       at or near """"
LINE 1: DROP DATABASE IF EXISTS ""
                            ^
: DROP DATABASE IF EXISTS ""

这是我的伙伴关系和学校表格的架构:

ActiveRecord::Schema.define(:version => 20140812210757) do


 create_table "partnerships", :force => true do |t|
  t.integer  "school_id"
  t.datetime "created_at",      :null => false
  t.datetime "updated_at",      :null => false
 end

 create_table "schools", :force => true do |t|
   t.string   "name"
   t.datetime "created_at",          :null => false
   t.datetime "updated_at",          :null => false
 end

end

0 个答案:

没有答案