Home > Back-end >  Multiple let declaration of the same helper method inside of an example group
Multiple let declaration of the same helper method inside of an example group

Time:10-26

Is there a way I can declare the same helper method, using let, inside of the same example group, but let it return different values in different expectation?

It would be something like

describe MyClass do 
  subject(:my_obj) { described_class.new(my_var) }
  describe '#my_method' do 
    context 'some context' do 
      let(:my_var) { 0 } 
      # expectation that involves my_var 

      let(:my_var) { 1 }
      # expectation that involves my_var 
    end 
  end 
end

A solution would be to provide different contexts for each of the expectation, but is it possible to solve this without adding more contexts?

CodePudding user response:

You could use the access to an example object and its metadata in the let block in combination with the tests metadata:

let(:my_var) do |example|
  example.metadata[:my_var]
end

context 'some context' do 
  it "my_var is 0", my_var: 0 do # <= here we set the necessary metadata
    ...
  end

  it "my_var is 1", my_var: 1 do # <= ... and again
    ...
  end
end
...

Unlike explicit sub-contexts, this way of writing specs is relatively rarely used, so it adds some mental overhead for anyone reading this code for the 1st time. But the thing is that deeply nested contexts aren't "free" either (at some nesting level it's just quite hard to understand what's going on), so flattening the spec with some "magic" might make sense - depending on the use case. Personally I'd use sub-contexts if I can and some white magic only if I must to...

CodePudding user response:

Maybe you can define an array an iterate over it, simply:

describe MyClass do 
  subject(:my_obj) { described_class.new(my_var) }
  describe '#my_method' do 
    context 'some context' do
      [0,1].each do |n|
        let(:my_var) { n } 
        # expectation that involves my_var 
      end
    end 
  end 
end
  • Related