How can I create and test has_and_belongs_to_many (HABTM) associations using Fabrication and RSpec?

I have 2 HABTM models:

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

belongs to the author (user)

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

      

Along with their respective manufacturers:

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

      

I am trying to write a test to check if there are article objects inside Category # show in RSpec

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

      

Both commented and uncommented tests throw this error:

undefined method 'find' for nil: NilClass (NoMethodError) undefined

method 'articles' for nil: NilClass (NoMethodError)

What should I do to be able to access the first Article object inside a Category I object that was fabricated, and vice versa?

+3


source to share


1 answer


It Fabricate.sequence

returns an integer when called , unless you pass a block to it. Instead, you need to generate the actual related objects. You should create your associations like this:



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

      

+6


source







All Articles