5

I'm trying to test a belongs_to association using rspec 3.0 but I keep running into the error

NoMethodError: undefined method `belong_to' for RSpec::Core

  it "should belong to a user" do
ride = Ride.new
user = User.new
user.rides << ride
expect(ride).to belong_to user

end

I can't find anything in the documentation for rspec 3.0 to test advanced associations. Help please!

user2635088
  • 1,598
  • 1
  • 24
  • 43
  • 1
    rspec doesn't have anything built in to test associations like that. Are you looking for a gem like `shoulda-matchers`? https://github.com/thoughtbot/shoulda-matchers – sevenseacat Jun 27 '14 at 01:48
  • Don't think shoulda-matchers works with Rspec 3.0 just yet - I ended up using respond_to instead. Thanks anyway! – user2635088 Jun 28 '14 at 13:45

3 Answers3

1

You can simply check the association:

it "belongs to a user" do
  ride = Ride.new
  user = User.new
  user.rides << ride
  expect(ride.user).to be user
end

In this context, the be matcher verifies object identity. So this will pass if and only if the user object has the same object_id. In this case, that is what you want and is semantically meaningful with how it is read.

Aaron K
  • 6,901
  • 3
  • 34
  • 29
1

shoulda-matchers is the gem that provides association, validation, and other matchers.

Look at this answer: Testing associations with rspec-rails 3.0.1 and shoulda doesn't work

Community
  • 1
  • 1
Fran Martinez
  • 2,994
  • 2
  • 26
  • 38
0

I ended up using

expect(ride).to respond_to :user

user2635088
  • 1,598
  • 1
  • 24
  • 43
  • well that doesn't test that the association exists - just that the instance will respond to the method symbol `:user`. – sevenseacat Jun 29 '14 at 13:22