1

I am trying to create a model named global_list. It will take a list which is associated with a user and a global_id which is associated with an item. I need to create a user (a list is created in a callback for this object) and an item (where a global_identification is created as a callback to item creation). Neither of the following solutions work in trying to create these associated objects before. Should they? Is there a better way to handle this? I have tried creating accessors for liked_item_list_id but that also didn't work.

FactoryGirl.define do
  factory :global_list do
    before(:create) {
       user=FactoryGirl.create(:user)
       mi=FactoryGirl.create(:item)
    }
    list_id user.liked_list_id
    global_id mi.global_id
  end
end

Will a block help?

FactoryGirl.define do
  factory :global_list do
    before(:create) {
      user=FactoryGirl.create(:user)
      mi=FactoryGirl.create(:item)
    }

    list_id { List.first.id }
    global_id { 3 } # 3 will be created at this point { mil.global_id } doesn't work
  end
end

I'm starting to think this is not possible with FactoryGirl. Any help would be appreciated?

4

3 回答 3

1

尝试这个。

   FactoryGirl.define do
      factory :global_list do
        before(:create) { |list|
           user=FactoryGirl.create(:user)
           mi=FactoryGirl.create(:item)
           list.list_id = user.liked_list_id
           list.global_id = mi.global_id
        }
      end
    end

它完全未经测试

于 2013-10-14T16:47:50.910 回答
1

这在 FactoryGirl 中是完全可能的,并且实际上经常使用。

在工厂中定义关联对象很简单,如下所示。不需要花哨的“之前”。

FactoryGirl.define do
  factory :global_list do
    user
    mi
    foo_attribute
    bar_attribute
  end

  factory :user do
    # blah
  end

  factory :mi do
    # blah
  end
end

使用上述代码,FactoryGirl 将首先创建所需的关联对象,并使用它们的 id 自动创建该对象。

于 2013-10-14T16:48:49.560 回答
0

这做到了:

FactoryGirl.define do
  factory :global_list do
    list_id { FactoryGirl.create(:user).liked_list_id }
    global_id { FactoryGirl.create(:item).global_id }
  end
end

Ruby 在这种情况下的块令人困惑。所以我问:这两个 FactoryGirl 声明之间的实际区别是什么

于 2013-10-15T00:41:02.940 回答