Skip to content

Commit

Permalink
Merge pull request #1002 from rspec/autoload_other_rspec_libs_master
Browse files Browse the repository at this point in the history
Autoload RSpec::Mocks and RSpec::Expectations. (master)
  • Loading branch information
myronmarston committed Jul 22, 2013
2 parents aec021f + 858593e commit 7ca98ac
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
32 changes: 19 additions & 13 deletions lib/rspec/core.rb
Expand Up @@ -175,19 +175,25 @@ def self.path_to_executable

end

MODULES_TO_AUTOLOAD = {
:Matchers => "rspec/expectations",
:Expectations => "rspec/expectations",
:Mocks => "rspec/mocks"
}

def self.const_missing(name)
case name
when :Matchers
# Load rspec-expectations when RSpec::Matchers is referenced. This allows
# people to define custom matchers (using `RSpec::Matchers.define`) before
# rspec-core has loaded rspec-expectations (since it delays the loading of
# it to allow users to configure a different assertion/expectation
# framework). `autoload` can't be used since it works with ruby's built-in
# require (e.g. for files that are available relative to a load path dir),
# but not with rubygems' extended require.
require 'rspec/expectations'
::RSpec::Matchers
else super
end
# Load rspec-expectations when RSpec::Matchers is referenced. This allows
# people to define custom matchers (using `RSpec::Matchers.define`) before
# rspec-core has loaded rspec-expectations (since it delays the loading of
# it to allow users to configure a different assertion/expectation
# framework). `autoload` can't be used since it works with ruby's built-in
# require (e.g. for files that are available relative to a load path dir),
# but not with rubygems' extended require.
#
# As of rspec 2.14.1, we no longer require `rspec/mocks` and
# `rspec/expectations` when `rspec` is required, so we want
# to make them available as an autoload. For more info, see:
require MODULES_TO_AUTOLOAD.fetch(name) { return super }
::RSpec.const_get(name)
end
end
18 changes: 18 additions & 0 deletions spec/rspec/core_spec.rb
Expand Up @@ -69,5 +69,23 @@
expect(File.executable? RSpec::Core.path_to_executable).to be_true
end
end

# This is hard to test :(. Best way I could come up with was starting
# fresh ruby process w/o this stuff already loaded.
it "loads mocks and expectations when the constants are referenced" do
code = "$LOAD_PATH.replace(#{$LOAD_PATH.inspect}); " +
'require "rspec"; ' +
"puts RSpec::Mocks.name; " +
"puts RSpec::Expectations.name"

result = `ruby -e '#{code}'`.chomp
expect(result.split("\n")).to eq(%w[ RSpec::Mocks RSpec::Expectations ])
end

it 'correctly raises an error when an invalid const is referenced' do
expect {
RSpec::NotAConst
}.to raise_error(NameError, /uninitialized constant RSpec::NotAConst/)
end
end

0 comments on commit 7ca98ac

Please sign in to comment.