开发者

Rspec - respond_to "user post" valid despite user is not valid (has_many/belongs_to association)

开发者 https://www.devze.com 2023-02-18 01:24 出处:网络
I don\'t understand something fairly basic with testing association (has_many / belongs_to ) with rspec.

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号