问题
我希望能够执行以下测试,但它失败了,因为我为事件使用的是构建而不是创建;
event_parent = build(:event_parent)
event = build(:event, event_parent: event_parent)
event_parent.events.size.should == 1
我真的不想使用 create,因为 a) 它比较慢 b) 构建事件的工厂有一些关联,我真的不想担心在测试数据库中的事情。
我尝试过的
我(错误地)假设如果我在 event_parent 模型上创建一个返回其事件的方法,那么它可能会在模型层而不是数据库层执行此操作。
我还将构建更改为为事件创建,这很有效,但正如我所说,对我的其余测试套件有一些不良副作用。
相关代码
事件父模型</p>
class EventParent < ActiveRecord::Base
has_many :events
end
事件模型
class Event < ActiveRecord::Base
belongs_to :event_parent
end
最佳答案
如果您想使用 ActiveRecord 指定您的关系,请查看 shoulda-matchers gem
describe Event do
let(instance) { Event.new }
it { expect(instance).to belong_to(:event_parent) }
end
describe EventParent do
let(instance) { EventParent.new }
it { expect(instance).to have_many(:events) }
end
关于ruby-on-rails - 如何使用不命中数据库的 Factory Girl 测试 Rails 中的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17966229/