scope woes in before block

8 views
Skip to first unread message

C S

unread,
Dec 24, 2020, 5:10:48 PM12/24/20
to rspec
Consider the following snippet:

before(:each) do
  #How can I see the fruits and veggies being operated on here?
end

['apples','pears', 'banananas'].each do |fruit|
  it "Can add #{fruit} to the fruit basket" do
    #fruit basket tests here
  end
end

['eggplant', 'lima beans', 'peas'].each do |veggie|
  it "Can remove #{veggie} from the fruit basket" do
    #veggie removal tests here
  end
end


Thanks for the help,

Cris

Phil Pirozhkov

unread,
Dec 24, 2020, 5:35:50 PM12/24/20
to Jack Royal-Gordon
> Consider the following snippet:
>
> before(:each) do
> #How can I see the fruits and veggies being operated on here?
> end

You can use the following trick:

['apples','pears', 'banananas'].each do |fruit|
context "do not omit this context, otherwise `let` would be called
in iterator, and the last would win' do
let(:fruit) { fruit } # This look a bit weird
it "Can add #{fruit} to the fruit basket" do
#fruit basket tests here
end
end
end

With the above, `fruit` will be available in `before`.

This snippet has two things that are not too obvious. Consider
approaching the same spec differently, e.g. with shared examples,
`all` matcher, etc. Or just not doing iteration and leaving spec
verbose , but readable (versus DRY).

- Phil
Reply all
Reply to author
Forward
0 new messages