Alex Smolov
Alex Smolov

Reputation: 1861

How does RSpec's expect... to change... to... work internally?

In RSpec, there is matcher expect{}.to change{}.to like

expect{employee.change_name}.to change{employee.name}.to "Mike"

It is very easy to read, but is not that easy to understand how it works from language standpoint. I suppose that expect, to and change are methods, but what objects are they called at? What curly braces mean in that case?

Thank you.

Upvotes: 0

Views: 136

Answers (2)

Peter Alfvin
Peter Alfvin

Reputation: 29419

change and expect are methods of self and to is a method of the result of executing change and expect. The {} expressions are blocks passed to change and expect.

The following illustrates the order of evaluation:

def self.to1(arg)
  puts "to1(#{arg})"
  "to1"
end

def self.to2(arg)
  puts "to2(#{arg})"
  "to2"
end

def self.expect
  puts "expect"
  yield
  self
end

def self.change
  puts "change"
  yield
  self
end

expect{puts "b1"}.to1 change{puts "b2"}.to2 "#{puts 'Mike' ; 'Mike'}"

which produces the following output:

expect
b1
change
b2
Mike
to2(Mike)
to1(to2)
 => "to1" 

Upvotes: 1

apneadiving
apneadiving

Reputation: 115541

They are blocks in ruby.

Basically the first step towards lambda expressions, basically anonymous functions.

Upvotes: 1

Related Questions