Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing polymorphic associations with RSpec

I'm writing RSpec code for polymorphic associations. I have two testing ideas that

  1. Use Factory Girl to build polymorphic associations
  2. Use rails methods to build polymorphic associations.

Here are the pieces of the code I wrote (relevant codes are at the bottom):

1) link_spec.rb, creating the association with FactoryGirl.

describe "Book links" do
  let(:book) { FactoryGirl.create(:book) }
  let(:book_link) { FactoryGirl.create(:book_link, linkable: book) }

  subject{ book_link }

  it { should be_valid }

  it { should respond_to(:url) }
  it { should respond_to(:linkable) }
  its(:linkable) { should eq book }
end

2) link_spec.rb, creating the association through rails methods.

describe "Book links" do
  let(:book) { FactoryGirl.create(:book) }
  let(:link) { book.links.create(url: "http://example.com") }

  subject { link }

  it { should be_valid }

  it { should respond_to(:url) }
  it { should respond_to(:linkable) }
  its(:linkable) { should eq book }
end

I feel the latter is testing better than the former, but have no confidence. Or are they equivalent to each other?


book.rb

class Book < ActiveRecord::Base
  has_many :links, as: :linkable
end

link.rb

class Link < ActiveRecord::Base
  belongs_to :linkable, polymorphic: true
end

factories.rb

factory :book do
  title "Foo bar"
  author "John"
end

factory :book_link, class: "Link" do
  association :linkable, factory: :book
  url "http://examle.com"
end
like image 423
tkymtk Avatar asked Feb 13 '14 08:02

tkymtk


1 Answers

I feel the latter is testing better than the former, but have no confidence.

If you intended to implicitly ask which was "better", then that question is not a good fit for StackOverflow.

Or are they equivalent to each other?

In the sense that the setup results in the same Link object being created, I would say that yes, they are equivalent. However, the second tests the association helper method set up for Book, which you may find desirable.

like image 136
Peter Alfvin Avatar answered Nov 10 '22 13:11

Peter Alfvin