Reputation: 3042
I'm new to ruby, I'm studying ruby by writing unittest with RSpec, and there is one line of code I can't understand in RSpec when define custom matcher.
RSpec::Matchers.define :be_a_multiple_of do |expected|
match do |actual|
do_the_math(actual, expected)
end
def do_the_math(actual, expected)
actual % expected == 0
end
end
as far as I know, ruby is a script language that the compiler read the code sequencly. that is said you must define the method before you use it. but in RSpec, when I define a custom matcher, I could define the helper method after I call it.
I have write the test code to test the fact that it will fail if I call the method before I define it and I also read a little source code from RSpec the define method actually is a wrapper of define_method and pass the delegate as block. but I still can't understand how this code work.
can somebody help me out? just a brief explaination of how this work
Upvotes: 1
Views: 1628
Reputation: 44675
Short explanation is: you are not calling this method yet in there, you are only saying to call it when you call be_a_multiple_of
matcher, and the method is already defined when that happens.
Parser is not checking whether methods are defined or not when declaring a method or block - as the method might be defined later or there might be a missing_method
fall_back.
Upvotes: 1