3
votes

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 an 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 fabricators:

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'm trying to write a test to check the presence of the 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 the commented and uncommented tests produce 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 the Category object I fabricated and vice-versa?

1

1 Answers

6
votes

Anytime you call Fabricate.sequence it returns an integer unless you pass a block to it. You need to generate the actual related objects instead. You should be generating 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