Published: April 02, 2022 • Updated: April 07, 2023 • 2 min read
describe block has two common syntaxes. Which should you use?
# With `RSpec` module name RSpec.describe TestedClass do end # Without module name describe TestedClass do end
👉Disclaimer: they both work. But I’m assuming since you’re here, you’re curious about the distinction, or want to make a reasoned choice.
TL;DR: I suggest using the
RSpec module name.
The global availability of
describe is called the Global Namespace
DSL. RSpec made
describe available on
Object, the default root of
all Ruby objects. The intent was to let us write specs without explicitly
And so, all of these are valid:
# With `RSpec` module name RSpec.describe TestedClass do end # Without module name describe TestedClass do end # Called on `Object` Object.describe TestedClass do end # Called on any object TestedClass.describe TestedClass do end
However, RSpec 3 introduced a configuration to disable this namespace:
# spec/spec_helper.rb config.expose_dsl_globally = false
In suites with this setting, only
RSpec.describe is valid. The other three
examples raise a
So, why use the namespace? I use it because it’s boring and pushes my code away from magic.
It’s the boring choice. It works in any RSpec test suite, regardless of configuration. It’s the syntax rspec-rails generates. You can borrow a spec from any other test suite or copy an example from the internet and it just works.
It’s the unmagical choice. Monkey patching is a contentious subjects in Ruby. It’s one of the best or worst features of the language, depending on who you ask. The module name lets me skip this debate at the cost of six communicative characters.
The choice is yours!
What are your thoughts on this? Let me know!
Join 100+ engineers who subscribe for advice, commentary, and technical deep-dives into the world of software.