使用rspec测试rails STI子类

Jon*_*son 3 testing tdd unit-testing rspec ruby-on-rails

给定一个继承自ActiveRecord :: Base的类,让我们将其称为Task,我有两个子类,它们使用标准的Rails单表继承来专门化任务的某些方面,Activity和Training.

在查看其他可用之后我对该选择充满信心,因为模型的实际数据是相同的,只是行为不同.非常适合STI.

可以创建,启动,进行和完成任务.这是这些转换中涉及的一些逻辑,尤其start()是要求基类的特化.

因为我正在做这个TDD,并开始使用完整测试覆盖的工作任务调用,我现在想知道如何继续.我有几个我想过的情景:

  1. 复制Task的测试并通过一些小的修改来端到端地测试Activity和Training,以测试它们的专业化.亲:这很快捷.Con:它复制代码,虽然这可能不是一个大问题,但是当专业化数量增加时.

  2. 拆分测试并保留大部分测试代码,task_spec.rb同时将专业化测试移动到相应子类的新规范中.Pro:保持测试干燥.Con:我在基础测试中实例化哪个类?

最后一个问题是什么在唠叨我.现在我已经设置了基类测试来从一个音乐会子类中随机创建一个类,但这是一个好的形式吗?它几乎让我想要采用方法1只是为了保持测试运行一致或者我必须找到一种方法来为测试套件选择随机种子的类随机性,这样我至少可以重复随机选择.

我猜这一定是人们遇到的常见问题,但我找不到关于这个问题的任何好消息.你对这件事有什么资源或想法吗?

bar*_*own 11

Using an rspec shared example (mentioned by Renato Zannon) would look like this:

Create a file in spec/support/. I'll call it shared_examples_for_sti.rb.

require 'spec_helper'

shared_examples "an STI class" do

  it "should have attribute type" do
    expect(subject).to have_attribute :type
  end

  it "should initialize successfully as an instance of the described class" do
    expect(subject).to be_a_kind_of described_class
  end

end
Run Code Online (Sandbox Code Playgroud)

In your _spec.rb file for each STI class and it's subclasses, add this line:

it_behaves_like "an STI class"
Run Code Online (Sandbox Code Playgroud)

If you have any other tests that you want to be shared across STI classes and subclasses just add them to the shared_examples.


Ren*_*non 5

您可以使用rspec 共享示例来测试在所有这些示例之间共享的行为(基本上,继承的行为,或您想要防止LSP违规的地方)。