【发布时间】:2020-04-23 01:41:15
【问题描述】:
我有一套规范要运行。我想每次使用不同的参数多次运行规范。例如,我正在针对两个不同的数据库版本测试 SQL 脚本。测试用例相同,但连接字符串不同。我将如何实现这一目标? 我是 RSpec 的新手,我能够让整个套件适用于一个版本。只需要知道如何使用不同的参数重新运行?
我查看了Class:RSpec::Core::Runner,但从文档中我不太清楚如何利用它来运行多次?
【问题讨论】:
我有一套规范要运行。我想每次使用不同的参数多次运行规范。例如,我正在针对两个不同的数据库版本测试 SQL 脚本。测试用例相同,但连接字符串不同。我将如何实现这一目标? 我是 RSpec 的新手,我能够让整个套件适用于一个版本。只需要知道如何使用不同的参数重新运行?
我查看了Class:RSpec::Core::Runner,但从文档中我不太清楚如何利用它来运行多次?
【问题讨论】:
您可以使用env variables 解决此问题。假设您要为两个不同的 MySQL 数据库运行 rspec。你可以像这样定义你的数据库连接:
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
【讨论】: