From ca5afbd0b3e5375c598acc9d9229f33c03558084 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 29 Jul 2019 14:30:16 -0500 Subject: [PATCH] Add Expect A Method To Be Called And Actually Call It as a ruby til --- README.md | 3 +- ...ethod-to-be-called-and-actually-call-it.md | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 ruby/expect-a-method-to-be-called-and-actually-call-it.md diff --git a/README.md b/README.md index 4e44afb..cae5e49 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_827 TILs and counting..._ +_828 TILs and counting..._ --- @@ -637,6 +637,7 @@ _827 TILs and counting..._ - [Editing Code In Pry](ruby/editing-code-in-pry.md) - [Encode A String As URL-Safe Base64](ruby/encode-a-string-as-url-safe-base64.md) - [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md) +- [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md) - [FactoryGirl Sequences](ruby/factory-girl-sequences.md) - [Fail](ruby/fail.md) - [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md) diff --git a/ruby/expect-a-method-to-be-called-and-actually-call-it.md b/ruby/expect-a-method-to-be-called-and-actually-call-it.md new file mode 100644 index 0000000..1a656aa --- /dev/null +++ b/ruby/expect-a-method-to-be-called-and-actually-call-it.md @@ -0,0 +1,42 @@ +# Expect A Method To Be Called And Actually Call It + +You can assert that a method is called without actually executing it. This is +often what `expect(...).to receive(:method_name)` is used for. If you do want +that method called, RSpec can accommodate you. + +Let's say we have the following two classes: + +```ruby +class Greeting + def self.say_hello + raise "Don't actually execute this" + puts "Hello" + end +end + +class GreetingService + def self.run + Greeting.say_hello + end +end +``` + +We can assert that `say_hello` gets called without actually raising the +exception (first `it` block). If we tack on `and_call_original` then RSpec will +make the assertion and execute the method (second `it` block). + +```ruby +describe "expect and call original" do + it "expect the message is received" do + expect(Greeting).to receive(:say_hello) + GreetingService.run + # passes + end + + it "expect and call original" do + expect(Greeting).to receive(:say_hello).and_call_original + GreetingService.run + # fails, RuntimeError + end +end +```