Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why undefined method "has_many" in Rspec example?

I am playing around with an Example on testing a has_many through association in RSpec. I am getting a

   1) Foo specifies items
       Failure/Error: subject.should have_many(:items)
       NoMethodError:
         undefined method `has_many?' for #
       # ./spec/models/foo_spec.rb:10

My question: Why would has_many be undefined?

The spec is:

describe Foo do
  it "specifies items" do
    subject.should have_many(:items)
  end
end

My models are:

foo.rb:

 class Foo < ActiveRecord::Base
   has_many :bars
   has_many :items, :through => :bars
 end

bar.rb:

class Bar < ActiveRecord::Base
  belongs_to :foo
  belongs_to :item
end

and item.rb:

class Item < ActiveRecord::Base
  has_many :foos, :through => :bars
  has_many :bars
end
like image 657
poseid Avatar asked Feb 23 '23 22:02

poseid


1 Answers

Well, there is no has_many? method on model objects. And rspec-rails does not provide such matcher by default. However, shoulda-matchers gem does:

describe Post do
  it { should belong_to(:user) }
  it { should have_many(:tags).through(:taggings) }
end

describe User do
  it { should have_many(:posts) }
end

(example from shoulda-matchers documentation)

Just add gem 'shoulda-matchers' to your Gemfile and you will be able to use that syntax.

like image 125
Victor Deryagin Avatar answered Feb 25 '23 11:02

Victor Deryagin