Hi Evan, Jack

I was attempting to simplify the closure rules for you, that the method was 
defined in the closure does not change the fact that the local variable cannot 
be accessed in the scope of the method definition e.g:

class A; end

A.class_eval do
a = ‘a’
def b
a
end
end

A.new.b

# NameError (undefined local variable or method `a' for #<A:..>)

This also does not work for similar reasons.

class A
a = ‘a’
def b
a
end
end

A.new.b
# NameError (undefined local variable or method `a' for #<A:…>)

RSpec defines classes for you, each describe / context is a class, each let is 
a method on that class, this explains why you can access those, and instance 
variables inside your methods, you are just defining additional methods on the 
classes RSpec creates for you.

Each test is run as a `class_exec` within an instance of that class. This is 
the special case that means you can access the class level local variables 
(from the shared example blocks) in their definition, you are creating blocks 
in the scope of the class, and then executing them in the context of the 
instance.

This is not unique to RSpec, it is Rubies rules of variable scoping.

Hope that helps
Jon Rowe
---------------------------
[email protected]
jonrowe.co.uk

On 25 June 2020 at 16:07, Evan Brodie wrote:
> Yes, Jack's analysis is correct. I placed my def method_name method 
> definition within the shared example block, not outside of it.
>
> I do a similar things when I write RSpec tests that used describe and context 
> blocks. I place method definition via def method_name within those blocks and 
> have no issues with accessing any of the let variables or even instance 
> variables of the test. When I'm outside of that describe or context block, 
> then naturally I cannot access that method anymore. Makes perfect sense. 
> Moreover, if I use a method outside of that block, then of course I cannot 
> access let variable from within the block. Neither of these situations are 
> what I'm dealing with here.
>
> Perhaps shared example blocks act differently than describe or context 
> blocks, in that their block parameters are not freely available to nested 
> method definition? I just want to make sure that we are all on the same page 
> though.
>
> On Thursday, June 25, 2020 at 10:46:09 AM UTC-4, Jack R-G wrote:

-- 
You received this message because you are subscribed to the Google Groups 
"rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rspec/dejalu-217-fc422353-ca9f-490f-977a-c6c70630454a%40jonrowe.co.uk.

Reply via email to