Skip to content

Instantly share code, notes, and snippets.

@myronmarston
myronmarston / Gemfile
Last active August 29, 2015 14:08
Example for vcr/vcr#450.
# A sample Gemfile
source "https://rubygems.org"
gem 'rspec', '~> 3.0'
gem 'vcr', '~> 2.9'
gem 'webmock', '~> 1.20'
@myronmarston
myronmarston / Rakefile
Created December 1, 2014 20:51
dotfiles Rakefile
require 'pathname'
HOME_DIR = Pathname("~").expand_path
def symlink_files_for_dir(to_symlink)
to_symlink = to_symlink.expand_path
to_symlink_root = Pathname("./to_symlink").expand_path
to_symlink.children.each do |child|
relative = child.relative_path_from(to_symlink_root)
symlink = HOME_DIR + ".#{relative}"
# you can pass an implementation block, and use expectations in the block:
expect(MyClass).to receive(:method) do |arg_1, arg_2|
expect(arg_1).to eq(2)
expect(arg_2).to eq(3)
end
# or you can wrap any block in the `satisfy` (also aliased to `an_object_satisfying`) to turn it into a matcher:
expect(MyClass).to receive(:method).with(an_object_satisfying { |arg| arg.even? })

The reason for this is that do...end blocks bind at a different precedence level than {...} blocks. Consider this expression:

expect { foo }.to change { x }

The { x } block binds to change, and is passed as a block to that method. However, if you use do...end:

expect { foo }.to change do
# A sample Gemfile
source "https://rubygems.org"
gem 'rspec', '~> 2.14.0'
Using `an_error_other_than` as an argument to `raise_error`
failing (FAILED - 1)
passing
Failures:
1) Using `an_error_other_than` as an argument to `raise_error` failing
Failure/Error: expect {
expected an error other than SyntaxError, got #<SyntaxError: SyntaxError> with backtrace:
# ./spec/raise_error_spec.rb:12:in `block (3 levels) in <top (required)>'
@myronmarston
myronmarston / Gemfile-3-1
Last active August 29, 2015 14:14
Demonstration of object allocation improvements in RSpec 3.2
source "https://rubygems.org"
gem 'rspec-core', "~> 3.1.7"
gem 'allocation_stats'

Haven't dived into RSpec but is it not possible for expect to accept either args or blocks, and process them internally?

First off, expect does accept either an arg or a block already. But if it's a block (or a proc/lambda arg), expect does not call the block automatically -- it just passes the block to the matcher and allows the matcher to call it if it wants. This is necessary because some matchers (the block matchers like raise_error, change, etc) must wrap the block in some extra logic to work properly because they deal in side effects, not expression return values.

require_relative '../order.rb'
describe Order do
def new_order(input)
order = Order.new
allow(order).to receive(:input).and_return(input)
order
end
it 'gets dish number as input' do
coverage