ggk
ggk

Reputation: 127

Rspect - Rails : how do you pass value from let into shared_example it_behaves_like

I wanted to use variable

RSpec.shared_examples 'something' do |event_name, event_params, action:|
  let(:event_params_data) do
    next instance_exec(&event_params) if event_params.respond_to?(:call)

    event_params
  end

  it 'it does something' do
    puts event_params
    puts event_name

    instance_exec(&action)
  end
end

and on another spec test file it calls the shared examples using it_behaves_like

describe '#do_alot_of_things' do

   let(:event_params){
     value: 'Value'
   }

   it_behaves_like 'something' 'event_name' {
     passed_value = event_params[:value]
   }

   action: {
     puts 'callback'
   }
end

however this wouldn't be possible I got an error that says

`event_params` is not available on an example group (e.g. a `describe` or `context` block). It is only available from within individual examples (e.g. `it` blocks) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc).

How would you recommend me so that I'm able to pass the value defined in the test to the shared_example ? moving the value into the shared_example wouldn't work since it would be pointless making the shared_example to be locked

Upvotes: 0

Views: 40

Answers (1)

wacko
wacko

Reputation: 3424

This is how you can use let inside/outside a shared example, and how to pass arguments to it:

RSpec.shared_examples "something" do |bar|
  let(:foo) { "foo" }

  it "uses let/argument" do
    expect(foo).to eq("foo")
    expect(bar).to eq("foo")
  end
end

RSpec.describe SomeClass do
  let(:bar) { "bar" }
  it_behaves_like "something", bar
end

Upvotes: 0

Related Questions