如何制作has_many:通过与灯具的关联?

时间:2011-09-08 18:28:37

标签: ruby-on-rails rspec factory-bot fixtures

我无法使用factory_girl,因为我正在测试太阳黑子并且需要真正的数据库。

修改:不。它可以与太阳黑子一起使用。我错了。

如何在灯具中建立has_many:through(a.k.a多对多)关联?

我谷歌并获得invalid solution

修改

最后我使用factory_girl。我google-copy-paste一个片段:

factory :tagging do 
    question { |a| a.association(:question) } 
    tag { |a| a.association(:tag) } 
end

(通过标记问题has_many标签,反之亦然)

效果很好。但它是什么? factory_girl的自述文件并不意味着这种语法。 有人能解释一下吗

3 个答案:

答案 0 :(得分:1)

如果它是一个经典的has_and_belongs_to_many关联,在关联模型中没有其他信息,我认为这些约定允许你像这样编写你的灯具:

#users.yml
john:
  first_name: John
  last_name: Doe
  hobbies: [swim, play_tennis]

#hobbies.yml
swim:
  name: Swim

play_tennis:
  name: Play Tennis

但我不完全确定!

答案 1 :(得分:1)

您可以找到factory_girl的官方文档,该文档非常完整,here

Here是一个不错的(较短的)博客文章,解释了factory_girl 2(将它与工厂女孩1进行比较)。

更新:

稍微解释一下代码:

 factory :tagging do
   association :tag
 end

将查找名为:tag的工厂并构建该对象,然后将其链接到对象中tag之间的关联belongs_to(例如:tagging) }}

请注意:这是默认工厂。如果您希望taggings分享tag,则需要执行类似

的操作
@tag = Factory(:tag)
@tagging_1 = Factory(:tagging, :tag => @tag)
@tagging_2 = Factory(:tagging, :tag => @tag)

希望这有帮助。

答案 2 :(得分:0)

我通过哈希has_many :through

merge进行测试时使用了灯具
# posts.yml
one:
  title: "Railscasts"
  url: "http://railscasts.com/"
  description: "Ruby on Rails screencasts"

# categories.yml
one:
  name: "magazine"
two:
  name: "tutorial"
three:
  name: "news"
four:
  name: "Ruby"

# posts_controller_test.rb
def test_post_create
  assert_difference 'Post.count' do
    post :create, post: posts(:one).attributes
     .merge(categories: [categories(:two), categories(:four)])
  end
end

在添加另一个灯具文件后,尝试了这个,它没有工作

# post_categories.yml
one:
  post: one
  category: two
two:
  post: one
  category: four

def test_post_create
  assert_difference 'Post.count' do
    post :create, post: posts(:one)
  end
end

puts posts(:one).attributes
# {"id"=>980190962, "url"=>"http://railscasts.com/", "title"=>"Railscasts", "description"=>"Ruby on Rails screencasts", "created_at"=>Thu, 14 May 2015 18:27:20 UTC +00:00, "updated_at"=>Thu, 14 May 2015 18:27:20 UTC +00:00}

puts posts(:one).attributes
      .merge(categories: [categories(:two), categories(:four)])
# {"id"=>980190962, "url"=>"http://railscasts.com/", "title"=>"Railscasts", "description"=>"Ruby on Rails screencasts", "created_at"=>Thu, 14 May 2015 18:30:23 UTC +00:00, "updated_at"=>Thu, 14 May 2015 18:30:23 UTC +00:00, "category_ids"=>[980190962, 1018350795]}