Skip to content
This repository
Newer
Older
100644 83 lines (63 sloc) 2.083 kb
0a9316ff »
2012-10-21 Adds additional documentation for mutating constants
1 ## Mutating Constants
2
3 ### Stubbing
e31f4a46 »
2012-06-02 Add cukes for new stub_const feature.
4
5 Support is provided for stubbing constants. Like with method stubs, the
7ab3d612 »
2012-06-02 Fix typo pointed out by @justinko.
6 stubbed constants will be restored to their original state when an
7 example completes.
e31f4a46 »
2012-06-02 Add cukes for new stub_const feature.
8
9 ``` ruby
10 stub_const("Foo", fake_foo)
11 Foo # => fake_foo
12 ```
13
14 Stubbed constant names must be fully qualified; the current module
15 nesting is not considered.
16
17 ``` ruby
18 module MyGem
19 class SomeClass; end
20 end
21
22 module MyGem
23 describe "Something" do
24 let(:fake_class) { Class.new }
25
26 it "accidentally stubs the wrong constant" do
27 # this stubs ::SomeClass (in the top-level namespace),
28 # not MyGem::SomeClass like you probably mean.
29 stub_const("SomeClass", fake_class)
30 end
31
32 it "stubs the right constant" do
33 stub_const("MyGem::SomeClass", fake_class)
34 end
35 end
36 end
37 ```
38
39 When you stub a constant that is a module or a class, nested
40 constants on the original module or class are not transferred
41 by default, but you can use the `:transfer_nested_constants`
42 option to tell rspec-mocks to transfer them:
43
44 ``` ruby
45 class CardDeck
46 SUITS = [:Spades, :Diamonds, :Clubs, :Hearts]
47 NUM_CARDS = 52
48 end
49
50 fake_class = Class.new
51 stub_const("CardDeck", fake_class)
52 CardDeck # => fake_class
53 CardDeck::SUITS # => raises uninitialized constant error
54 CardDeck::NUM_CARDS # => raises uninitialized constant error
55
56 stub_const("CardDeck", fake_class, :transfer_nested_constants => true)
57 CardDeck::SUITS # => [:Spades, :Diamonds, :Clubs, :Hearts]
58 CardDeck::NUM_CARDS # => 52
59
60 stub_const("CardDeck", fake_class, :transfer_nested_constants => [:SUITS])
61 CardDeck::SUITS # => [:Spades, :Diamonds, :Clubs, :Hearts]
62 CardDeck::NUM_CARDS # => raises uninitialized constant error
63 ```
64
0a9316ff »
2012-10-21 Adds additional documentation for mutating constants
65 ### Hiding
66
67 Support is also provided for hiding constants. Hiding a constant temporarily
68 removes it; it is restored to its original value after the test completes.
69
70 ```ruby
71 FOO = 42
72 hide_const("FOO")
73 FOO => NameError: uninitialized constant FOO
74 ```
75
76 Like stubbed constants, names must be fully qualified.
77
78 Hiding constants that are already undefined has no effect.
79
80 ```ruby
81 hide_const("NO_OP")
82 ```
Something went wrong with that request. Please try again.