I'm writing RSpec code for polymorphic associations. I have two testing ideas that
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With