Error testing ActiveRecord association

90 Views Asked by At

I have a Rails 5.2 app with the following models:

class Foo < ApplicationRecord
  has_many :bars
end

class Bar < ApplicationRecord
  belongs_to :foo
end

I'm using rspec-rails (3.7.2), shoulda-matchers (3.1.2). I have a spec to test the association:

describe Foo do
  it { is_expected.to have_many :bars }
  it { should have_many :bars }
end

No matter which syntax I use I get the the same error:

Foo should have many :bars
Failure/Error: it { is_expected.to have_many :bars }
  expected #<Foo:0x007f9f813ce650> to respond to `has_many?` # ./spec/models/foo_spec.rb:4

Foo should have many :bars
Failure/Error: it { should have_many :bars }
  expected #<Foo:0x007f9f84ad3970> to respond to `has_many?` # ./spec/models/foo_spec.rb:5

I followed the instructions here, but still get the error. I have pushed my sample project to Github: https://github.com/fredwillmore/shoulda_matchers_test

1

There are 1 best solutions below

1
nopu On

I'm not sure but I think you need to define type of rspec like:

RSpec.describe Foo, type: :model do
   it { is_expected.to have_many :bars }
end