DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Prettier Syntax For Expectations In Rspec (IMHO)
my_object.should_receive(:my_method).with(my_param).and_return(my_result)
looks quite ugly for me. I would prefer syntax, that closer mimics the expected method call and may look like this:
expect_sent(my_object).my_method(my_param) == my_result
Here is example for the functionality:
it "expect_send should add expectaction" do
user = Object.new
expect_sent(User).find(1) == user
User.find(1).should == user
end
Here is naive implementation:
module SpecHelper
def expect_sent receiver
ExpectSent.new receiver
end
end
class ExpectSent
instance_methods.each { |x|
case x.to_sym
when :inspect, :__send__, :__id__, :object_id
else undef_method x
end
}
def initialize receiver
@receiver = receiver
end
def method_missing name, *args
AndReturn.new @receiver.should_receive(name).with(*args)
end
end
class AndReturn
def initialize from
@from = from
end
def == result
@from.and_return result
end
end





