thank_you
thank_you

Reputation: 11107

Rspec testing Belongs to and has many

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

Upvotes: 9

Views: 13115

Answers (2)

lucianosousa
lucianosousa

Reputation: 8374

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

Upvotes: 20

Benoît
Benoît

Reputation: 15010

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

Upvotes: 2

Related Questions