ruby-grape/grape · error · ArgumentError
a block is required
Error message
a block is required
What it means
Grape::Testing::RunBeforeEach lets tests register endpoint setup hooks with `before_each`, which must be given a block to store. Calling `before_each` without a block (e.g. intending to query or reset hooks) raises ArgumentError ('a block is required') instead of silently registering nothing.
Source
Thrown at lib/grape/testing.rb:14
# frozen_string_literal: true
module Grape
module Testing
module RunBeforeEach
def run
self.class.run_before_each(self)
super
end
end
module ClassMethods
def before_each(&block)
raise ArgumentError, 'a block is required' unless block
@before_each ||= []
@before_each << block
end
def reset_before_each
@before_each&.clear
end
def run_before_each(endpoint)
superclass.run_before_each(endpoint) unless self == Grape::Endpoint
@before_each&.each { |blk| blk.call(endpoint) }
end
end
Grape::Endpoint.prepend(RunBeforeEach)
Grape::Endpoint.extend(ClassMethods)
endView on GitHub (pinned to 22d7975629)
Solutions
- Always pass a block: `before_each { |endpoint| endpoint.stub :helper, :value }`.
- To clear hooks, call `reset_before_each` instead of a bare before_each.
- When the block is optional in your own helpers, guard with `before_each(&block) if block`.
Example fix
# before
before_each # raises
# after
before_each { |endpoint| endpoint.instance_variable_set(:@current_user, user) }
reset_before_each # when you need to clear instead Defensive patterns
Strategy: validation
Validate before calling
before_each(&block) if block # conditional registration reset_before_each # clearing hooks instead of a bare before_each
Type guard
def block_given?(...) = block_given? # use Ruby's block_given? before calling before_each
Prevention
- Always pass `&blk` through helper wrappers: `def with_user(user, &blk) before_each(&blk) end`.
- Use `reset_before_each` in after-hooks to clear state between specs.
- Lint specs for bare `before_each` lines.
When it happens
Trigger: `before_each` bare inside an RSpec setup. `before_each(&:stub_something)`-style shorthand that yields nil instead of a block. Guard code that calls before_each conditionally with the block accidentally dropped.
Common situations: Conditionally adding test hooks where the block variable is nil. Refactoring specs from blocks to method references and losing the `&`. Copying spec boilerplate incompletely.
Related errors
- type #{type} should support coercion via `[]`
- #declared is not available prior to parameter validation
- Representation of type #{representation.class} cannot be mer
- Status code must be Integer or Symbol.
- Argument must be a file path
AI-assisted analysis of ruby-grape/grape@22d7975629 (2026-08-21).
Data as JSON: /api/errors/a4c43177b72eaa5f.
Report an issue: GitHub.