Ruby on rails 如何配置具有复杂依赖关系的工厂

Ruby on rails 如何配置具有复杂依赖关系的工厂,ruby-on-rails,rspec,Ruby On Rails,Rspec,我可以让这个测试与一个糟糕的rspec设计一起工作。我正试图将我的依赖项转移到工厂,但它不起作用。我想不出一种方法既可以调用数据服务,又可以使用数据服务所有者工厂自动创建它 以下是规范文件: describe Foo do shared_context "notify" do let!(:subscriber) { FactoryGirl.create(:subscriber) } let!(:foo) { FactoryGirl.create(:foo) } le

我可以让这个测试与一个糟糕的rspec设计一起工作。我正试图将我的依赖项转移到工厂,但它不起作用。我想不出一种方法既可以调用
数据服务
,又可以使用
数据服务所有者
工厂自动创建它

以下是规范文件:

describe Foo do

  shared_context "notify" do
    let!(:subscriber) { FactoryGirl.create(:subscriber) }
    let!(:foo) { FactoryGirl.create(:foo) }
    let!(:message) { FactoryGirl.create(:message) }
    let!(:bar) { FactoryGirl.create(:bar) }
  end

  describe "#notify(subscriber)" do
  include_context "notify"

    it "notifies bars" do
      bar.foo = foo #shouldn't have to do this
      bar.save #shouldn't have to do this
      expect { foo.notify_on_subscribe(subscriber) }.to change { Notification.all.count }.by(1)
    end
end
我已经成功地测试了所有的工厂。这里是
数据\u服务\u所有者
工厂:

factory :bar do
    boolean_attr true
    employee
    foo #if I put FactoryGirl.create(:foo) here, it is not associated with the same foo object I defined in the let! statement
  end

谢谢。

您应该能够通过执行以下操作将其关联到let块中

let!(:bar) { FactoryGirl.create(:bar, foo: foo) }
这应该与上面创建的foo相关联