How to pass a variable as parameter to shared examples in Rspec

Stanley Meng
2 min readJun 26, 2019

--

I knew that I can pass a parameter to shared_exmples, here is an example: https://relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

However, in the example, the parameters are passed as a String,

RSpec.describe SomeClass do
include_examples "some example", "parameter1"
include_examples "some example", "parameter2"
end

How if I want to pass a variable, something like:

RSpec.describe SomeClass do
include_examples "some example", i_am_a_variable
end

I have a real world case which bothers me a while. I want to pass @fdqn to the shared_examples.

describe 'A Class' do
before do
@fqdn = a_function_return_fqdn()
end
context 'access via FQDN', smoke: true do
# I want to pass the @fqdn to the include_examples
include_examples 'check services', @fqdn # this will NOT work
end
end
shared_examples 'check services' do |fqdn|
it 'enabled and running' do
expect(fqdn).to do something #pseudo code
end
end

To make it work, I found a workaround, put the ‘let’ block in the include_examples block, it works for me.

describe 'A Class' do
before do
@fqdn = a_function_return_fqdn()
end
context 'access via FQDN', smoke: true do
# I want to pass the @fqdn to the include_examples
include_examples 'check services' do
let(:fqdn) {@fqdn}
end
end
end
shared_examples 'check services' do
it 'enabled and running' do
expect(fqdn).to do something #pseudo code
end
end

One more thing… in case you might have notice… the shared_example can access @fqdn directly, therefore, the below code would work too.

describe 'A Class' do
before do
@fqdn = a_function_return_fqdn()
end
context 'access via FQDN', smoke: true do
include_examples 'check services'
end
end
shared_examples 'check services' do
it 'enabled and running' do
expect(@fqdn).to do something #pseudo code
end
end

But, as I mentioned at the beginning, here I wanted to figure out how to pass a parameter. Hope it’s clearer now.

--

--

Responses (1)