Hommer Smith
Hommer Smith

Reputation: 27852

Correct way of testing "associations" with Rspec?

I am trying to test the following scenario:

-> I have a model called Team which it just makes sense when it has been created by a User. Therefore, each Team instance has to be related to a User.

In order to test that, I have done the following:

describe Team do

...

  it "should be associated with a user" do
    no_user_team = Team.new(:user => nil)
    no_user_team.should_not be_valid
  end

...

end

Which forces me to change the Team model as:

class Team < ActiveRecord::Base
  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :user

  validates_presence_of :name
  validates_presence_of :user

  belongs_to :user
end

Does this seem correct to you? I am just worried of make the :user attribute as accessible (mass assignment).

Upvotes: 50

Views: 44251

Answers (4)

Abeyance
Abeyance

Reputation: 153

RSpec is a ruby test framework, and not a rails framework. belongs_to is a rails construct, and not a ruby construct. Gems like shoulda-matchers connect ruby and rails things and help you write good tests.

Having the above in mind and following official documentation, should help you stay up to date and understand what you are writing.

So, below is what I would write.

User model:

RSpec.describe User, type: :model do
  context 'associations' do
    it { should have_many(:teams).class_name('Team') }
  end
end

Team model:

RSpec.describe Team, type: :model do
  context 'associations' do
    it { should belong_to(:user).class_name('User') }
  end
end

Upvotes: 1

juliangonzalez
juliangonzalez

Reputation: 4381

class MicroProxy < ActiveRecord::Base
    has_many :servers
end

describe MicroProxy, type: :model do
    it { expect(described_class.reflect_on_association(:servers).macro).to eq(:has_many) }
end

Upvotes: 1

Lu&#237;s Ramalho
Lu&#237;s Ramalho

Reputation: 10208

I usually use this approach:

describe User do
  it "should have many teams" do
    t = User.reflect_on_association(:teams)
    expect(t.macro).to eq(:has_many)
  end
end

A better solution would be to use the gem shoulda which will allow you to simply:

describe Team do
  it { should belong_to(:user) }
end

Upvotes: 69

urbanczykd
urbanczykd

Reputation: 319

  it { Idea.reflect_on_association(:person).macro.should  eq(:belongs_to) }
  it { Idea.reflect_on_association(:company).macro.should eq(:belongs_to) }
  it { Idea.reflect_on_association(:votes).macro.should   eq(:has_many) }

Upvotes: 27

Related Questions