【问题标题】:RSpec: Can I disable certain shared examples tests?RSpec:我可以禁用某些共享示例测试吗?
【发布时间】:2020-06-13 19:00:26
【问题描述】:

我在 RSpec 中使用shared_examples 为许多不同的 rspec 文件运行一组针对多种上传格式(例如 yml、csv 等)的测试。但是,我运行这些共享示例的 rspec 测试之一不支持 csv 上传格式。是否可以在这个 rspec 文件的共享示例中禁用/跳过某些 csv 测试?

【问题讨论】:

  • 更好的解决方案可能是重组测试。您能给我们提供一个示例,说明它们的结构吗?
  • 所以我有很多控制器测试来测试上传文件。因此,在我共享的示例“测试上传格式”中:我测试了格式正确的 yml/csv/xls,测试了格式不正确的 yml/csv/xls 等。除了一个不支持的控制器之外,所有其他控制器都支持所有三种格式.csv。正因为如此,我不想只为我的这个控制器重写所有的 yml 和 xls 测试,所以我想利用除 csv 测试之外的共享示例测试。这更有意义吗?
  • yaml、csv 和 xls 的共享示例是否都非常相似?还是它们非常不同?

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


【解决方案1】:

一种选择是将允许的上传格式添加到您的控制器,并让测试内省您的控制器。这可能会使生产和测试代码都干涸。

class ApplicationController
  def self.upload_formats
    [:yaml, :json, :csv]
  end
end

class OtherController < ApplicationController
  def self.upload_formats
    [:yaml, :json]
  end
end

shared_examples 'it accepts uploads' do
  let(:formats) { described_class.upload_formats }

  ...
end

这可能太干了;如果self.upload_formats 缺少格式,测试将无法捕捉到它。


您可以在共享示例中添加一个标志并传递它应该检查的格式。如果每种格式的测试都相似,这就变成了一个简单的循环。

shared_examples 'it accepts uploads' do |formats: [:yaml, :json, :csv]|
  formats.each do |format|
    let(:format) { format }

    context "in #{format}" do
      ...
    end
  end
end

大多数测试将保持不变并使用默认值。

it_behaves like 'it accepts uploads'

您的例外可以指定它们的格式。

it_behaves like 'it accepts uploads', formats: [:yaml, :json]

如果比这更复杂,您可能希望将共享测试分解为针对每种格式的单独测试。原始共享测试运行所有单独的共享测试。离群值可以随意挑选。

shared_examples 'it accepts uploads in all formats' do
  it_behaves_like 'it accepts yaml uploads'
  it_behaves_like 'it accepts json uploads'
  it_behaves_like 'it accepts csv uploads'
end

同样,大多数测试保持不变。

it_behaves_like 'it accepts uploads in all formats'

并且异常值可以单独运行测试。

it_behaves_like 'it accepts yaml uploads'
it_behaves_like 'it accepts json uploads'

这具有分解可能是大型共享示例的额外优势,并允许进一步自定义单个共享示例。


为了方便,您可以将两者结合起来。

shared_examples 'it accepts uploads' do |formats: [:yaml, :json, :csv]|
  it_behaves_like 'it accepts yaml uploads' if formats.include?(:yaml)
  it_behaves_like 'it accepts json uploads' if formats.include?(:json)
  it_behaves_like 'it accepts csv uploads'  if formats.include?(:csv)
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多