Passing parameters to an rspec shared example

you can use let.

let(:result)     { build_result({some_parameters}) }

This creates an instance variable that you can use in your test later.

Accord to documentation on let,

When you have to assign a variable instead of using a before block to create an instance variable, use let. Using let the variable lazy loads only when it is used the first time in the test and get cached until that specific test is finished.

BAD

describe '#type_id' do
  before { @resource = FactoryGirl.create :device }
  before { @type     = Type.find @resource.type_id }

  it 'sets the type_id field' do
    expect(@resource.type_id).to equal(@type.id)
  end
end

GOOD

describe '#type_id' do
  let(:resource) { FactoryGirl.create :device }
  let(:type)     { Type.find resource.type_id }

  it 'sets the type_id field' do
    expect(resource.type_id).to equal(type.id)
  end
end

If you wanted to pass arguments to the shared_example spec file, you should use something like

it_behaves_like 'SHARED_EXAMPLE_NAME', { params1: param2, param2: param2 }

You can also pass the parameters without hash encapsulation. It depends on how you are going to utilize that param into your shared file. In my case, I have to call the API with the dynamic params.

RSpec.shared_examples 'SHARED_EXAMPLE_NAME' do |params = {}|

FYI: You cannot pass Factory data as param into the shared_example spec file. You have to explicitly call the factory into the shared_example spec file.


You can pass arguments to shared examples like this:

shared_examples_for "A result" do |argument|
 # some tests with argument
end

And then pass in my_argument like this:

it_behaves_like "A result", my_argument