5
我正在爲多態關聯編寫RSpec代碼。我有兩個測試的想法,使用RSpec測試多態關聯
- 使用工廠女孩打造多態關聯
- 使用軌方法來構建多態關聯。
下面是我寫的代碼的片(相關碼是在底部):
1)link_spec.rb,創建與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,通過rails方法創建關聯。
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
我覺得後者測試比前者好,但沒有信心。 或者它們是否相等?
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