factory_girl_rails:创建关联子项时,工厂构建的模型实例的 has_many 关联未填充
我使用 factory_girl_rails 而不是固定装置。这是我的模型:
class User < ActiveRecord::Base
has_many :tasks
belongs_to :project
end
class Task < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
class Project < ActiveRecord::Base
has_many :users
has_many :tasks
end
这是相关的工厂:
Factory.define :task do |t|
t.association :user
t.association :project
t.after_create {|t| t.user.tasks << t}
t.after_create {|t| t.project.tasks << t}
end
在集成测试中我这样做:
scenario "user with tasks from one project is assigned another task from the same project" do
user = Factory.create :user
(1..5).each { Factory.create(:task, :user => user, :project => user.project)}
visit_project_path user.project
correctly_fill_in_new_task_fields
click_button "Create task" #creates a new task for the above user
assert user.tasks.size == 6 #currently fails
end
我遇到的问题是,在场景运行后 user.tasks.size == 5
,但是 Task .where(:user_id => user.id).size == 6
。我将不胜感激任何帮助。
I'm using factory_girl_rails instead of fixtures. Here are my models:
class User < ActiveRecord::Base
has_many :tasks
belongs_to :project
end
class Task < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
class Project < ActiveRecord::Base
has_many :users
has_many :tasks
end
Here's the relevant factory:
Factory.define :task do |t|
t.association :user
t.association :project
t.after_create {|t| t.user.tasks << t}
t.after_create {|t| t.project.tasks << t}
end
In an integration test I do this:
scenario "user with tasks from one project is assigned another task from the same project" do
user = Factory.create :user
(1..5).each { Factory.create(:task, :user => user, :project => user.project)}
visit_project_path user.project
correctly_fill_in_new_task_fields
click_button "Create task" #creates a new task for the above user
assert user.tasks.size == 6 #currently fails
end
The problem that I have is that after the scenario runs user.tasks.size == 5
, but Task.where(:user_id => user.id).size == 6
. I'd appreciate any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,这更有可能是由于 ActiveRecord 的工作方式造成的。您的控制器从数据库中获取用户并创建一个新的 User 实例。现在您的控制器和您的测试引用了两个不同的用户,这就是您的测试永远看不到更改的原因。
在再次检查有多少任务之前,您需要对
user
调用reload
。旁注:一些 ORM 提供了一个身份映射(特殊类型的注册表)来解决这个问题(实际上......快速谷歌似乎表明 Rails 3 最近在源代码中添加了一个身份映射。我不使用 AR ,所以不确定如何启用它)。
Actually, this is more likely due to the way ActiveRecord works. Your controller fetches the user from the database and creates a new instance of User. Now your controller and your test have references to two different users, which is why your test never sees the changes.
You'll need to call
reload
onuser
before checking how many tasks there are again.Side-note: some ORMs provide an identity map (special type of registry) to get around this problem (actually... a quick Google seems to indicate Rails 3 recently got an Identity Map added to the source. I don't use AR, so not sure how you enable it).