Skip to content

Commit

Permalink
Pass block to expect as needed
Browse files Browse the repository at this point in the history
RSpec's `expect` has two forms:

- scalar: `expect(result).to be_truthy`
- block: `expect { thunk }.not_to raise_error(RuntimeError)`

So what happens when you mix them?

```ruby
thunk = -> { 1 / 0 }
expect(thunk).not_to raise_error(RuntimeError)
```

If you do that, RSpec complains:

> The implicit block expectation syntax is deprecated, you should pass a
> block rather than an argument to `expect` to use the provided block
> expectation matcher or the matcher must implement
> `supports_value_expectations?`

The easy solution is to pass the Proc as a block, using `&`:

```
thunk = -> { 1 / 0 }
expect(&thunk).not_to raise_error(RuntimeError)
```
  • Loading branch information
mike-burns committed Nov 17, 2023
1 parent 9b9b24f commit 388f93f
Show file tree
Hide file tree
Showing 4 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion spec/acceptance/defining_methods_inside_a_factory_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def generate_name
end
end

expect(bad_factory_definition).to raise_error(
expect(&bad_factory_definition).to raise_error(
FactoryBot::MethodDefinitionError,
/Defining methods in blocks \(trait or factory\) is not supported \(generate_name\)/
)
Expand Down
2 changes: 1 addition & 1 deletion spec/acceptance/modify_factories_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,6 @@
end
end

expect(modify_unknown_factory).to raise_error(KeyError)
expect(&modify_unknown_factory).to raise_error(KeyError)
end
end
2 changes: 1 addition & 1 deletion spec/factory_bot/definition_proxy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
proxy = FactoryBot::DefinitionProxy.new(definition)
invalid_call = -> { proxy.static_attributes_are_gone "true" }

expect(invalid_call).to raise_error(
expect(&invalid_call).to raise_error(
NoMethodError,
"undefined method 'static_attributes_are_gone' in 'broken' factory\n" \
"Did you mean? 'static_attributes_are_gone { \"true\" }'\n"
Expand Down
2 changes: 1 addition & 1 deletion spec/support/matchers/raise_did_you_mean_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
raise_error(KeyError, /Did you mean\?/)
end

expect(actual).to matcher
expect(&actual).to matcher
end
end

0 comments on commit 388f93f

Please sign in to comment.