运行 rspec 使用不同参数多次测试套件

Run rspec test suite multiple times with different parameters

我有一套 运行 的规范。我想 运行 多次使用不同的参数。例如,我正在针对两个不同的数据库版本测试 SQL 脚本。测试用例相同,但连接字符串不同。我将如何实现这一目标? 我是 RSpec 的新手,我能够让整个套件为一个版本工作。只需要知道如何使用不同的参数重新运行?

我查看了 Class:RSpec::Core::Runner,但从文档中我不太清楚如何利用它多次 运行?

你可以用env variables解决这个问题。假设您想 运行 rspec 用于两个不同的 MySQL 数据库。您可以像这样定义数据库连接:

db_client = Mysql2::Client.new(database: ENV['DB_NAME'])

现在您可以 运行 您的 rspec 像这样:

DB_NAME=your_custom_db_name rspec
DB_NAME=other_db_name rspec

您可以使用shared_examples来实现您想要的。

这是一个例子:

RSpec.describe 'shared_examples' do
  shared_examples 'is palendrome' do |word|
    it 'is equal to itself if reversed' do
      expect(word.reverse).to eq(word)
    end
  end

  context 'with the word racecar' do
    # Runs every example is the shared_examples block and passes
    include_examples 'is palendrome', 'racecar'
  end

  context 'with the word apple' do
    # Runs every example is the shared_examples block but fails
    include_examples 'is palendrome', 'apple'
  end
end