Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 975
thank_you Avatar asked Nov 15 '12 01:11

thank_you


People also ask

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.

Is RSpec used for unit testing?

RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the "behavior" of an application being tested.

Is RSpec TDD or BDD?

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. RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD.

Do RSpec tests run in parallel?

Run RSpec Tests in Parallel This is “Parallel Testing”. Parallel Testing gives you the same benefits as running a multi-threaded application and helps you reduce the run time of your test suite, resulting in faster build times and faster releases.


1 Answers

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
like image 78
lucianosousa Avatar answered Oct 05 '22 23:10

lucianosousa