Rspec - Using variable defined in a let statement in another let statement

3.3k Views Asked by At

In my RSpec test, I have defined multiple methods using let() syntax. I have encountered a scenario where I need to use variable defined inside a let statement into another let statement inside same describe block.

 context 'Reuse the name of first car in the second car' do
    it_behaves_like 'some car test' do

      let(:car1) do {
          name1: "#{testcase['Car']}_#{Time.now.round}",
          car_model: testcase['Toyota']
      }

      end

      let(:car2) do {
          name2: name1
      }
      end
    end
  end

As you can see I want to use the exact name value I defined name1 inside :car1 for name2 inside :car2. The above syntax throws me following error

NameError:
       undefined local variable or method `name1' for #<RSpec::

How do I use exact value of name1 in :car2? Any ideas..

3

There are 3 best solutions below

1
Sebastián Palma On BEST ANSWER
let(:name1) { "#{testcase['Car']}_#{Time.now.round}" }

let(:car1) { { name1: name1, car_model: testcase['Toyota'] } }

let(:car2) { { name2: name1 } }

So name1 is also now a lazy variable to initialized when is called, if not for car1, then for car2.

If the Time.now is a problem, you can leave the value of name1 as testcase['Car'] and then just interpolate the value of Time.now.

0
spickermann On

name1 is a key in the hash defined as car1, therefore you need to use the hash syntax to get its value:

let(:car1) do 
  {
    name1: "#{testcase['Car']}_#{Time.now.round}",
    car_model: testcase['Toyota']
  }
end

let(:car2) do 
  {
    name2: car[:name1]
  }
end

Please note that this only answers your question on how to extract the value, I do not suggest writing specs like that. If both cars should share the same name than Sebastian's answer is probably clearer and easier to understand.

0
Nondv On

let definitions work just fine with each other.

You defined two things: car1 and car2. Code is throwing an error about name1. You just didnt define it.

I guess you need to read more about ruby Hash and Symbol.