Michael Durrant
Michael Durrant

Reputation: 96484

rspec before :each - how to do on one line instead of do..end block?

My code uses a before :each block:

before :each do
  @unsorted=[1,5,6,7,4,5,8,4,2,5,2]
end 
it "contains an unsorted an array" do
  test_array = BubbleSort.new(@unsorted)
  expect(test_array.contents).to eq [1,5,6,7,4,5,8,4,2,5,2]
end 

I'd like the before :each code to be inline but using

before :each {@unsorted=[1,5,6,7,4,5,8,4,2,5,2]}

gives:

syntax error, unexpected '{', expecting keyword_
end (SyntaxError)

How can I fix this?

Upvotes: 2

Views: 1032

Answers (3)

vgoff
vgoff

Reputation: 11313

This is not idiomatic of Ruby, but it is allowed.

before :each do puts "something here" end

The default argument for before I believe is :each so you could just leave it out.

The stronger precedence of {} blocks as compared to do..end blocks will require us to use parenthesis so that the block is not associated with the argument rather than the method. If the argument were a method that does something with a block it would then be allowed, and perhaps confusing.

Of course, your error is specifically from the parser seeing you are trying to apply a block (the unexpected {) to a symbol.

Upvotes: 2

sawa
sawa

Reputation: 168101

When there is a block written as {}, Ruby's syntax does not allow omission of the parentheses around the arguments. You need to do:

before(:each){@unsorted=[1,5,6,7,4,5,8,4,2,5,2]}

Upvotes: 7

Michael Durrant
Michael Durrant

Reputation: 96484

One answer was to use before instead of before :each i.e.

before {@unsorted=[1,5,6,7,4,5,8,4,2,5,2]}

Upvotes: 2

Related Questions