【问题标题】:How to fabricate and test has_and_belongs_to_many (HABTM) associations using Fabrication and RSpec?如何使用 Fabrication 和 RSpec 制造和测试 has_and_belongs_to_many (HABTM) 关联?
【发布时间】:2012-04-21 03:39:33
【问题描述】:

我有 2 个 HABTM 模型:

class Article < ActiveRecord::Base
  attr_accessible :title, :content
  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
  has_and_belongs_to_many :categories

  validates :title, :presence => true
  validates :content, :presence => true
  validates :author_id, :presence => true

  default_scope :order => 'articles.created_at DESC'
end

class Category < ActiveRecord::Base
  attr_accessible :description, :name
  has_and_belongs_to_many :articles

  validates :name, :presence => true
end

Article 属于作者(用户)

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me
  attr_accessible :name

  has_many :articles, :foreign_key => 'author_id', :dependent => :destroy
end

连同他们各自的制造商:

Fabricator(:user) do
  email { sequence(:email) { |i| "user#{i}@example.com" } }
  name { sequence(:name) { |i| "Example User-#{i}" } }
  password 'foobar'
end

Fabricator(:article) do
  title 'This is a title'
  content 'This is the content'
  author { Fabricate(:user) }
  categories { Fabricate.sequence(:category) }
end

Fabricator(:category) do
  name "Best Category"
  description "This is the best category evar! Nevar forget."
  articles { Fabricate.sequence(:article) }
end

我正在尝试编写一个测试来检查 RSpec 中 Category#show 中是否存在 Article 对象

before do
  @category = Fabricate(:category)
  visit category_path(@category)
end

# it { should have_link(@category.articles.find(1).title :href => article_path(@category.articles.find(1))) }
@category.articles.each do |article|
  it { should have_link(article.title, :href => article_path(article)) }
end

注释和未注释的测试都会产生这个错误:

nil:NilClass (NoMethodError) 未定义的未定义方法 'find'

方法 'articles' 用于 nil:NilClass (NoMethodError)

我应该怎么做才能访问我制造的 Category 对象中的第一个 Article 对象,反之亦然?

【问题讨论】:

    标签: ruby-on-rails rspec capybara fabrication-gem


    【解决方案1】:

    任何时候你调用Fabricate.sequence它都会返回一个整数,除非你传递一个块给它。您需要生成实际的相关对象。你应该像这样生成你的关联:

    Fabricator(:article) do
      title 'This is a title'
      content 'This is the content'
      author { Fabricate(:user) }
      categories(count: 1)
    end
    
    Fabricator(:category) do
      name "Best Category"
      description "This is the best category evar! Nevar forget."
      articles(count: 1)
    end
    

    【讨论】:

    • 如果我想从不同的 Fabricator 创建文章/类别?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    相关资源
    最近更新 更多