Jake Worth

Jake Worth

RSpec.describe vs. describe

Published: April 02, 2022 2 min read

  • ruby

RSpec’s 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 an informed choice.

TL;DR: I suggest using the RSpec module name.

Explanation

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 specifying the RSpec module.

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 NoMethodError.

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.

Monkey patching and magic are contentious subjects in Ruby. They are some of the best and 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!


Get better at programming by learning with me. Subscribe to my newsletter for weekly ideas, creations, and curated resources from across the world of programming. Join me today!