How to re-use (share) Rspec examples across files
Here is my real situation. The product I’m working on is deployed to both AWS and Azure. The product is exactly the same in both platform, so I do not want to waste time maintain two sets of Rspec examples which do the same tests. I want the examples can be shared by the specs.
All the sample codes in https://relishapp.com/rspec have the shared_examples block and the describe block in the same file. It doesn’t work for me. The deployment procedures for AWS and Azure are different. Alright, in order to share the Rspec examples, but still do different setup/teardown for different platform. I find out a way, maybe not perfect though. Check it out.
I assume these three files are put in the same folder.
# Put your examples in a file, NOTE, do not put in any spec file, for #example, shared_test_examples.rbshared_examples 'shared demo examples' do
it 'is shared test' do
# eip is passed by the let() block in the spec files
expect(eip).to eq '10.1.1.1'
end
end==============# Spec A, let's name it test_a_spec.rb. Please pay attention to the #relative path of the requirerequire_relative './shared_test_examples.rb'
describe 'AWS Use' do
before do
# Do AWS deployment, e.g. get the eip of the instance
@eip = '10.1.1.1'
end
include_examples 'shared demo examples' do
# let() block pass the eip as parameter to the shared examples
let(:eip) {@eip}
end
end=========# Spec B, let's name it test_b_spec.rb. Please pay attention to the #relative path of the requirerequire_relative './shared_test_examples.rb'
describe 'Azure Use' do
before do
# Do Azure deployment, e.g. get the eip
@eip = '10.1.1.1'
end
include_examples 'shared demo examples' do
# let() block pass the eip as parameter to the shared examples
let(:eip) {@eip}
end
end