FactoryGirl ID协会

时间:2013-09-12 16:19:34

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

您好,我正在尝试测试,但我遇到了一些问题。首先,提交conn.rb

FactoryGirl.define do
    factory :conn, class: Connection do
    from_id         1
    to_id       4
    end
end

第二个文件leg.rb

FactoryGirl.define do
factory :leg_le, class: Leg do
    association :connection_id, factory: :conn
    from_id         1
    to_id           2
end
end

我的目标是使用leg_le ID创建conn

 conn=FactoryGirl.create(:conn)
 leg=FactoryGirl.create(:leg_le)

似乎是创建,但connection_idnil

1 个答案:

答案 0 :(得分:0)

您可以尝试:

FactoryGirl.define do
    factory :connection do
        from_id    1
        to_id      4
    end
end

FactoryGirl.define do
    factory :leg do
        association :connection, factory: :connection
        from_id         1
        to_id           2
    end
end

然后

FactoryGirl.create(:leg).connection_id
    # => 1 or whatever your connection_id is

或(如果您想在其他地方重用连接实例):

connection = FactoryGirl.create(:connection)
FactoryGirl.create(:leg, :connection=> connection).connection_id
    # => 1 or whatever your connection_id is