Question

I don't understand something fairly basic with testing association (has_many / belongs_to ) with rspec.

Associations in models:

user has_many :posts
post belongs_to :user 

I set a user with no attributes and test if a post should respond_to user. The test is valid however the user is not valid (and not created).

I know that respond_to only test the presence of the post through association but how can it exist without a valid user? Can someone explain me why? Thank you!

user_spec.rb

require 'spec_helper'

describe User do

  describe "post associations"

    before(:each) do
      @user = User.create(@attr) #no attribute is set
    end

    it "should have a post attribute" do
      @user.should respond_to(:posts)
    end

  end

end
Was it helpful?

Solution

The user does respond to posts, it just returns an empty array. Try this in a rails console:

> @user = User.new
> @user.posts
=> []

A better test may be:

@user.posts.should be_empty

Honestly testing rails relationships is not usually recommended as you are essentially testing rails it self which is already very well tested.

However, shoulda provides some nice matchers that work in rspec to check that relationships are set up correctly:

it {should have_many(:posts)}

Check it out on github: https://github.com/thoughtbot/shoulda

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top