0

我有一个属于用户的活动记录模型:

class Profile < ActiveRecord::Base
  belongs_to :user
  ...
end

在我的模型测试中,我有一个 before_all 块:

before :all do
  @profile = build(:user)
end

每个测试用例都通过访问器方法获得概要文件类的干净副本,该访问器方法获取对象的深层克隆:

def profile
  @profile.dup
end

好又快,而不是每次都打电话给工厂:)

但是我的问题是,因为配置文件及其关联在内存中,所以配置文件中不存在 user_id,因此内存中的用户对象也不会被复制。

所以 while@profile.user是一个对象:

<User id: nil, email 'test@test.com '.../>

@profile.dup.user

nil

如果我在哪里打电话@profile.save那么神奇

@profile.dup.user变成:

<User id: 1, email 'test@test.com '...>

除了覆盖我的私有方法以将用户显式复制到克隆上之外,还有一种方法可以让导轨进行提升。即使该方法的行为与被持久化的dup方法相同?@profile

感谢您的任何建议。

4

0 回答 0