On Dec 21, 5:24 am, Arne Brasseur <[email protected]> wrote:
> I find myself wanting to do something like this, and I'm curious to
> hear what others think of this pattern.
>
> describe "a hash with two values" do
> let(:hsh) {{ xxx: 1, yyy: 2 }}
>
> context "with a third value added" do
> alias _hsh hsh
> let(:hsh) { _hsh.merge(zzz: 3) }
>
> it "should contain all three values" do
> hsh.should == { xxx:1, yyy:2, zzz:3 }
> end
> end
> end
>
> The alias there is a workaround, ideally I'd like hsh to reference the
> previous value when inside that block : let(:hsh) { hsh.merge(zzz: 3)
>
> } , but with the current implementation that gives infinite recursion.
>
> Another way is to use a before block, but I don't like the mixing of
> let and before in this case.
>
> describe "a hash with two values" do
> let(:hsh) {{ xxx: 1, yyy: 2 }}
>
> context "with a third value added" do
> before { hsh.merge!(zzz: 3) }
>
> it "should contain all three values" do
> hsh.should == { xxx:1, yyy:2, zzz:3 }
> end
> end
> end
>
> I don't want to use a different name, because I have shared examples
> that reference it. I know there are ways to side step the issue.
>
> Have you used something like this before? Would you consider it bad practice?
>
> - Arne
> _______________________________________________
> rspec-users mailing list
> [email protected]http://rubyforge.org/mailman/listinfo/rspec-users
I wouldn't consider it a bad practice, per se, but certainly in the
context of your trivial example it seems like overkill. I assume
you're dealing with a larger example, where it may or may not be
overkill.
You mention that the current implementation causes infinite recursion
for this `let(:hsh) { hsh.merge(zzz: 3) }`. I think that any
implementation will have this problem--`let` simply defines a memoized
method, and like with any method, when you call it within the body of
the method, it causes recursion. Nothing we can do about that.
What you can do is use plain methods to do something like:
describe "a hash with two values" do
def hsh
@hsh ||= { xxx: 1, yyy: 2 }
end
context "with a third value added" do
def hsh
@hsh ||= super.merge(zzz: 3)
end
it "should contain all three values" do
hsh.should == { xxx:1, yyy:2, zzz:3 }
end
end
end
HTH,
Myron
--
You received this message because you are subscribed to the Google Groups
"rspec" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.