【问题标题】:Testing polymorphic associations with RSpec使用 RSpec 测试多态关联
【发布时间】:2014-02-13 08:25:42
【问题描述】:

我正在为多态关联编写 RSpec 代码。我有两个测试想法

  1. 使用 Factory Girl 构建多态关联
  2. 使用 rails 方法建立多态关联。

这是我写的代码片段(相关代码在底部):

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

链接.rb

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

工厂.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

【问题讨论】:

    标签: ruby-on-rails rspec polymorphic-associations


    【解决方案1】:

    我觉得后者的测试比前者好,但没有 信心。

    如果您打算含蓄地问哪个“更好”,那么这个问题不适合 StackOverflow。

    或者它们是等价的吗?

    从某种意义上说,设置会导致创建相同的Link 对象,我会说是的,它们是等价的。但是,第二个测试为 Book 设置的关联辅助方法,您可能会觉得这很可取。

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多