4

Currently, with rspec-rails (2.14.2), I test my associations in model specs with the shoulda (3.5.0) gem like so:

# app/models/user.rb
class User < ActiveRecord::Base

  belongs_to :school

end

# spec/models/user_spec.rb
describe User do

  it { should belong_to :school }

end

After some research, I hit a wall trying to make association-related assertions work (they all seem to fail).

Error message:

1) User
     Failure/Error: it { is_expected.to belong_to :school }
     NoMethodError:
       undefined method `belong_to' for #<RSpec::ExampleGroups::School:0x007f8a4c7a68d0>
     # ./spec/models/user.rb:4:in `block (2 levels) in <top (required)>'

So my questions are:

  1. Can you test associations without the shoulda gem? This doesn't seem possible based on what I've seen with the "expect" syntax.
  2. Does the shoulda gem break with rspec 3.0.1 for everyone? Is there a workaround?
Randy Burgess
  • 4,835
  • 6
  • 41
  • 59

3 Answers3

4

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

The shoulda gem (which we also make) is for using shoulda-matchers with Test::Unit (and also provides some nice things like contexts and the ability to use strings as test names). But if you're on RSpec, you'll want to use shoulda-matchers, not shoulda.

Elliot Winkler
  • 2,336
  • 20
  • 17
4

This is the way it works, now with the shoulda-matchers gem and the "expect" syntax

describe User, type: :model do
  it { is_expected.to belong_to :school }
end
Randy Burgess
  • 4,835
  • 6
  • 41
  • 59
2

I do not believe you need the gem for the basic associations.

You might be having an issues if you haven't actually assigned your user to your school. You need to populate the foreign key, not just use the relationship without having done that.

So you may need to do

@school = School.new
@user = User.new
@school.users << @user

it { should belong_to :school } # within the user block

or

expect(@user).to belong_to @school
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • The should-matchers test the associations as they are assigned in the model. That works fine with rails-rspec 2.x. Thus, my question is whether I can do the same test with an expect syntax. – Randy Burgess Jun 04 '14 at 12:54
  • I agree, why to type additional 3 more lines of rspec to make sure you put 1 (e.g. belong_to) in code that you are testing? – Katarzyna May 14 '15 at 23:10