Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 547
Hommer Smith Avatar asked Mar 30 '13 21:03

Hommer Smith


People also ask

How do I run a test in RSpec?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

What type of testing is RSpec?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.

What RSpec method is used to create an example?

The describe Keyword The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument.

Is RSpec BDD or TDD?

RSpec is a Behavior-Driven Development tool for Ruby programmers. BDD is an approach to software development that combines Test-Driven Development, Domain Driven Design and Acceptance Test-Driven Planning.


1 Answers

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 
like image 128
Luís Ramalho Avatar answered Sep 24 '22 03:09

Luís Ramalho