Rspec testing Belongs to and has many

10,686

Solution 1

You need to save both models to validate this relationship, also, you can use shoulda gem.

The code looks like:

describe Link do
  it { should belong_to(:post) }
end

describe Post do
  it { should have_many(:links) }
end

Solution 2

You need to assign your link to your post otherwise, if you do @post.links, you will get a empty array ([]), which [].first returns nil. Then your try nil.url and then you get url is an undefined method for NilClass.

@post = Post.new(day: "Day 1", content: "Test")
@link = Link.new(title: "google", url: "google.com")
@post.links << @link
Share:
10,686
thank_you
Author by

thank_you

Updated on September 14, 2022

Comments

  • thank_you
    thank_you about 1 year

    I'm running a rspec test to make sure that two models are associated between each other with has_many and belongs_to. Here is my test below.

    describe "testing for has many links" do
      before do
        @post = Post.new(day: "Day 1", content: "Test")
        @link = Link.new(post_id: @post.id, title: "google", url: "google.com")
      end
    
      it "in the post model" do
        @post.links.first.url.should == "google.com"
      end
    end
    

    The test is telling me that url is an undefined method. What's wrong with my test? Or did I just miss something basic.

    The model file for Post

    has_many :links
    

    The model file for Link

    belongs_to :post
    

    On top of that, the link model has the attribute post_id

  • thank_you
    thank_you almost 11 years
    Would my updated code in the question work as well? That was the original code I had, I just missed adding post_id: @post.id.
  • oldergod
    oldergod almost 11 years
    Since you only do new, your object are not saved. So when you do @post.links, the program will try to load those links from the database. You don't have no saved ones so it will be empty.
  • lucianosousa
    lucianosousa almost 3 years
    Couple of years later I'm coming here just to mention that if you want to test it, you are testing the Rails framework. It's a useless test. I'm not doing this anymore ;)