@@ -167,6 +167,78 @@ RSpec.describe Hash do
167
167
end
168
168
```
169
169
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
+
170
242
## The ` rspec ` Command
171
243
172
244
When you install the rspec-core gem, it installs the ` rspec ` executable,
0 commit comments