[rspec-users] Augmenting a previous 'let' value

Arne Brasseur arne.brasseur at gmail.com
Fri Dec 21 13:24:38 UTC 2012


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


More information about the rspec-users mailing list