Ruby on rails Factorygirl通过模型有一个关联

Ruby on rails Factorygirl通过模型有一个关联,ruby-on-rails,testing,rspec,factory-bot,Ruby On Rails,Testing,Rspec,Factory Bot,我有一个带有的模型,它通过另一个模型关联 class Publisher has_many :books end class Book belongs_to :publisher has_one :author end class Author belongs_to :book has_one :publisher, :through => :book end 在我的Rails代码中,我可以毫无问题地调用author.publisher,这样一切都可以正常工作。然

我有一个带有
的模型,它通过另一个模型关联

class Publisher
  has_many :books
end

class Book
  belongs_to :publisher
  has_one :author
end

class Author
  belongs_to :book
  has_one :publisher, :through => :book
end
在我的Rails代码中,我可以毫无问题地调用
author.publisher
,这样一切都可以正常工作。然而,在我的规范中(使用Rspec和FactoryGirl),这种关联似乎不起作用。以下是我对FactoryGirl的定义:

Factory.define :author do |a|
  a.association :book
end

Factory.define :book do |b|
  b.association :publisher
end

Factory.define :publisher
end
(省略了工厂中的大多数属性)

现在在我的规范中,我可以做以下事情

pub = Factory(:publisher)
book = Factory(:book, :publisher => pub)
author = Factory(:author, :book => book)

author.book # => Returns book
author.book.publisher # => Returns publisher 
author.publisher # => nil

那么为什么我的
通过
关联不起作用呢?

工厂女孩
/
工厂女孩轨道
4.1.0中,以下内容对我有效:

工厂.rb

FactoryGirl.define do

  factory :author do
    book
  end

  factory :book do
    publisher
  end

  factory :publisher do
  end

end
在rails控制台中:

pub = FactoryGirl.create(:publisher)
#=> #<Publisher id: 1, created_at: "2013-01-30 13:35:26", updated_at: "2013-01-30 13:35:26">
book = FactoryGirl.create(:book, :publisher => pub)
#=> #<Book id: 1, publisher_id: 1, created_at: "2013-01-30 13:36:23", updated_at: "2013-01-30 13:36:23">
author = FactoryGirl.create(:author, :book => book)
#=> #<Author id: 1, book_id: 1, created_at: "2013-01-30 13:36:57", updated_at: "2013-01-30 13:36:57">
author.book
#=> #<Book id: 1, publisher_id: 1, created_at: "2013-01-30 13:36:23", updated_at: "2013-01-30 13:36:23">
author.book.publisher
#=> #<Publisher id: 1, created_at: "2013-01-30 13:35:26", updated_at: "2013-01-30 13:35:26">
author.publisher
#=> #<Publisher id: 1, created_at: "2013-01-30 13:35:26", updated_at: "2013-01-30 13:35:26">

如果您使用
Publisher.create
Book.create
Author.create
而不是
FactoryGirl.create
,也会发生同样的情况,因此这不是FactoryGirl行为,而是rails行为,与如何通过
关联缓存

哪个版本的
factory\u girl
/
factory_girl_rails
您在使用吗?4.1.0版适合我。
Publisher Load (0.2ms)  SELECT "publishers".* FROM "publishers"
  INNER JOIN "books" ON "publishers"."id" = "books"."publisher_id"
  WHERE "books"."id" = 1 LIMIT 1