Reputation: 11896
Suppose I create an Rspec shared example group with one parameter (the business purpose of the tests are irrelevant, it is an overly simplified version of my current codebase):
shared_examples "some example group" do |parameter|
it "does something" do
puts "parameter=#{parameter}"
print_the_parameter
end
def print_the_parameter
puts "parameter=#{parameter}"
end
end
I am able to access the parameter
as a variable just fine with the it
test block. However, I am running into an "undefined local variable or method" when I try to access parameter
from a method. Why is that? I have proven in my codebase (and is prevalently shown in Rspec documentation) that the parameter is available in test blocks, lifecycle methods like before
, and in let
variable declarations. But why not helper methods?
Thank you.
Upvotes: 0
Views: 129
Reputation: 356
This is standard Ruby scoping, the parameter passed to the block is available within the block's closure. So the evaluated string "parameter=#{parameter}"
being within the closure works just fine.
What you're trying to do the same as is this:
b = "Hi!"
def a
puts b
end
a()
# NameError (undefined local variable or method `b' for main:Object)
The solution is to wrap parameter in a let
, (note I strongly encourage using a different name to prevent confusion about precedence.) e.g.
let(:param) { parameter }
This is the same (roughly) as doing:
b = "Hi!"
def a
puts b
end
define_method(:b) { b }
a()
# Hi!
# => nil
Upvotes: 1