4

I have a few sets of rspecs that all include some shared examples. I would like those shared examples to then include other shared examples, if the original spec had some variable set. Basically this is what I'm trying to do.

Example:

File: spec/test_spec.rb

describe 'some thing' do
  let(:some_feature) { true }

  describe 'some tests' do
    include_examples "shared_tests" 
  end
end

File spec/shared/shared_tests.rb

shared_examples_for "shared_tests" do
  include_examples "feature_specific_tests" if some_feature
end

As expected, this is throwing an error like this:

undefined local variable or method `some_feature`

Is there a way to do this? I thought perhaps I could define @some_feature in a before(:all) block and then use if @some_feature in the shared_examples, but that is always nil.

1 Answer 1

3

Rewriting the answer to make it a little clearer:

You had this:

File: spec/test_spec.rb

describe 'some thing' do
  let(:some_feature) { true }

  describe 'some tests' do
    include_examples "shared_tests" 
  end
end

File spec/shared/shared_tests.rb

shared_examples_for "shared_tests" do
  include_examples "feature_specific_tests" if some_feature
end

Change it to:

File: spec/test_spec.rb

describe 'some thing' do

  describe 'some tests' do
    include_examples "shared_tests" do
      let(:some_feature) { true }
    end
  end
end

File spec/shared/shared_tests.rb

shared_examples "shared_tests" do
  if some_feature
    it_should_behave_like "feature_specific_tests"
  end

  # rest of your tests for shared example group
  # 'a logged in registered user goes here
end

And it'll all work nicely :-)

Sign up to request clarification or add additional context in comments.

9 Comments

Ok, this makes sense. The question is more like how to only use it_should_behave_like "some tests" if some_feature as the variable is outside of its scope
right - see the bottom code block - just shift your let(:some_feature) line down from where you had it into a block you feed your first shared examples call... compare the block I put at the bottom to your original block up top. You're just effectively passing a truthy value through to the shared example set, in a block, which will then be available within the second group...
I've laid it out like you described, but I still get an undefined method error in the shared_examples... Somehow I'm not grasping this.
Hmm... this is how I've got it done in several test suites... let me go over the code again and make sure I've not done anything stupid.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.