Sha256: 773dcef157c67a3af789bb1506d7fcaad67377a0ec3f1392688e6373786dd070

Contents?: true

Size: 1.63 KB

Versions: 10

Compression:

Stored size: 1.63 KB

Contents

## Stubbing Constants

Support is provided for stubbing constants. Like with method stubs, the
stubbed constants will be restored to their original state when an
example completes.

``` ruby
stub_const("Foo", fake_foo)
Foo # => fake_foo
```

Stubbed constant names must be fully qualified; the current module
nesting is not considered.

``` ruby
module MyGem
  class SomeClass; end
end

module MyGem
  describe "Something" do
    let(:fake_class) { Class.new }

    it "accidentally stubs the wrong constant" do
      # this stubs ::SomeClass (in the top-level namespace),
      # not MyGem::SomeClass like you probably mean.
      stub_const("SomeClass", fake_class)
    end

    it "stubs the right constant" do
      stub_const("MyGem::SomeClass", fake_class)
    end
  end
end
```

When you stub a constant that is a module or a class, nested
constants on the original module or class are not transferred
by default, but you can use the `:transfer_nested_constants`
option to tell rspec-mocks to transfer them:

``` ruby
class CardDeck
  SUITS = [:Spades, :Diamonds, :Clubs, :Hearts]
  NUM_CARDS = 52
end

fake_class = Class.new
stub_const("CardDeck", fake_class)
CardDeck # => fake_class
CardDeck::SUITS # => raises uninitialized constant error
CardDeck::NUM_CARDS # => raises uninitialized constant error

stub_const("CardDeck", fake_class, :transfer_nested_constants => true)
CardDeck::SUITS # => [:Spades, :Diamonds, :Clubs, :Hearts]
CardDeck::NUM_CARDS # => 52

stub_const("CardDeck", fake_class, :transfer_nested_constants => [:SUITS])
CardDeck::SUITS # => [:Spades, :Diamonds, :Clubs, :Hearts]
CardDeck::NUM_CARDS # => raises uninitialized constant error
```

Version data entries

10 entries across 10 versions & 5 rubygems

Version Path
tnargav-1.3.3 vendor/bundle/ruby/1.9.1/gems/rspec-mocks-2.11.3/features/stubbing_constants/README.md
tnargav-1.2.3 vendor/bundle/ruby/1.9.1/gems/rspec-mocks-2.11.3/features/stubbing_constants/README.md
fragrant-0.0.5 vendor/bundle/ruby/1.9.1/gems/rspec-mocks-2.11.3/features/stubbing_constants/README.md
gem_repackager-0.1.0 support/gems/rspec-mocks-2.11.1/features/stubbing_constants/README.md
rspec-mocks-2.11.3 features/stubbing_constants/README.md
librarian-puppet-0.9.4 vendor/gems/ruby/1.8/gems/rspec-mocks-2.11.1/features/stubbing_constants/README.md
rspec-mocks-2.11.2 features/stubbing_constants/README.md
librarian-puppet-0.9.3 vendor/gems/ruby/1.8/gems/rspec-mocks-2.11.1/features/stubbing_constants/README.md
rspec-mocks-2.11.1 features/stubbing_constants/README.md
rspec-mocks-2.11.0 features/stubbing_constants/README.md