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