Skip to content
This repository was archived by the owner on Nov 30, 2024. It is now read-only.

Commit 8112643

Browse files
committed
Add section describing scope.
After reading http://therealadam.com/2015/03/01/its-not-your-fault-if-your-tools-confuse-you/, I realized we do a poor job documenting the way the scopes work so this will hopefully help.
1 parent 2c4ae5c commit 8112643

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,78 @@ RSpec.describe Hash do
167167
end
168168
```
169169

170+
## A Word on Scope
171+
172+
RSpec has two scopes:
173+
174+
* **Example Group**: Example groups are defined by a `describe` or
175+
`context` block, which is eagerly evaluated when the spec file is
176+
loaded. The block is evaluated in the context of a subclass of
177+
`RSpec::Core::ExampleGroup`, or a subclass of the parent example group
178+
when you're nesting them.
179+
* **Example**: Examples, and any other blocks with per-example semantics
180+
(such as a `before(:example)` hook), are evaluated in the context of
181+
an _instance_ of the example group class to which the example belongs.
182+
Examples are _not_ executed when the spec file is loaded; instead,
183+
RSpec waits to run any examples until all spec files have been loaded,
184+
at which point it can apply filtering, randomization, etc.
185+
186+
To make this more concrete, consider this code snippet:
187+
188+
``` ruby
189+
RSpec.describe "Using an array as a stack" do
190+
def build_stack
191+
[]
192+
end
193+
194+
before(:example) do
195+
@stack = build_stack
196+
end
197+
198+
it 'is initially empty' do
199+
expect(@stack).to be_empty
200+
end
201+
202+
context "after an item has been pushed" do
203+
def build_stack
204+
super.push :item
205+
end
206+
207+
it 'allows the pushed item to be popped' do
208+
expect(@stack.pop).to eq(:item)
209+
end
210+
end
211+
end
212+
```
213+
214+
Under the covers, this is (roughly) equivalent to:
215+
216+
``` ruby
217+
class UsingAnArrayAsAStack < RSpec::Core::ExampleGroup
218+
def build_stack
219+
[]
220+
end
221+
222+
def before_example
223+
@stack = build_stack
224+
end
225+
226+
def it_is_initially_empty
227+
expect(@stack).to be_empty
228+
end
229+
230+
class AfterAnItemHasBeenPushed < self
231+
def build_stack
232+
super.push :item
233+
end
234+
235+
def it_allows_the_pushed_item_to_be_popped
236+
expect(@stack.pop).to eq(:item)
237+
end
238+
end
239+
end
240+
```
241+
170242
## The `rspec` Command
171243

172244
When you install the rspec-core gem, it installs the `rspec` executable,

0 commit comments

Comments
 (0)