Is there a way to access let methods from the same example group

8 views
Skip to first unread message

Sergei Gerasenko

unread,
Feb 9, 2023, 7:58:37 AMFeb 9
to rspec
Hi,

I have an unusual case where I need to do something like this:

  def helper
    context 'another context' do
      let(:node_params) do
        # I would like to merge with the
        # the other node_params hash here
        # but this doesn't work because 
        # there's no super() yet.
        super().merge(
          {
            :y => 1,
          }
        )
      end

      it 'some test' do
      end
    end
  end

  describe 'something' do
    # define node params
    let(:node_params) do
      {
        :x => 1,
      }
    end
    # call helper
    helper
  end


The helper function needs to get access to the node_params from the calling context (:x => 1), but i can't seem to be to do it. If I surround the call to helper with another context, then it will work.

Curious if there are elegant solutions to this. Thanks!!

Phil Pirozhkov

unread,
Feb 9, 2023, 8:21:40 AMFeb 9
to rs...@googlegroups.com
It should be `def self.helper`. This has nothing to do with the missing `super`.

This passes:
```
RSpec.describe do
  def self.helper
    context 'another context' do
      let(:foo) { super() + 1 }

      it 'some test' do
        expect(foo).to eq(2)

      end
    end
  end

  describe 'something' do
    let(:foo) { 1 }
    helper
  end
end
```

Running your example, there's an error message that gives a hint:
```
`helper` 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)
```

Jon Rowe

unread,
Feb 9, 2023, 8:28:24 AMFeb 9
to rspec
Hi

I'd expect the code you provided to work, and having tested it in a plain spec it does.

I assume you mean without the context inside the helper you'd like to override the node_params, which you can't do because its like (and in fact is) redefining a method, where as describe/context blocks create inherited classes.

You could of course, use a before block to mutate node params in this example however.

Cheers
Jon
Reply all
Reply to author
Forward
0 new messages