如何将这个特定的构造函数放入 FactoryGirl 对象中?

How to put this specific constructor into a FactoryGirl object?

我正在尝试将该创建代码放入 FactoryGirl 中。

所以基本上在这里,你可以看到我的 class 用户有一个方法来根据他的信息、id、created_at 等创建图片....

.

class User 
has_many :pictures

def create_picture
    picture = Picture.new(
        user_id: self.id,
        store_dir: get_user_medias_path,
    )
    picture.save!
    picture
end

def get_user_media_path
   "u/#{self.id}/#{self.created_at}
end


end

然后我尝试将其放入 FactoryGirl 对象中,如下所示

FactoryGirl.define do
  factory :user do
    sequence(:name) { |i| "flav_#{i}" }
  end

  factory :picture do
    store_dir user.get_user_medias_path
    remote_url "http://lorempixel.com/600/600/animals/internet#{user.id}/"
    association :user     
  end
end

但如您所料,他找不到 user.id 或 user.method。

我应该如何才能在图片对象中引用用户属性?

我迷路了。任何帮助都将受到欢迎。 =)

在你的代码中 user 是在工厂定义的上下文中调用的,它没有这样的方法。您需要在实际构建的对象上调用 user,图片。

为此,您应该将计算值包装在块中:

factory :picture do
  store_dir { user.get_user_medias_path }
  remote_url { "http://lorempixel.com/600/600/animals/internet#{user.id}/" }
  association :user     
end

请参阅文档中的 lazy and dependent 属性。