Other Mock/Stub Frameworks
If you prefer to use a mocking framework other than RSpec’s built in framework, you can do this quite simply. RSpec currently supports use of the following frameworks out of the box (in alphabetical order):
RSpec supports use of a single framework per project, because these frameworks (including) RSpec’s own, tend to add methods to Object that might or might not work well together. To choose a mock framework other than rspec, simply add the following to spec/spec_helper.rb (or any file that gets loaded when you run your examples):
Spec::Runner.configure do |config| config.mock_with :rr end
Valid options are :flexmock, :mocha, :rspec (of course), and :rr.
Even more “other” frameworks
If you have a different framework that is not supported directly by RSpec, you can easily choose that framework instead by creating an adapter and telling RSpec where to find it. Here is RSpec’s own adapter as an example:
require 'spec/mocks/framework' require 'spec/mocks/extensions' module Spec module Adapters unless defined?(MockFramework) module MockFramework include Spec::Mocks::ExampleMethods def setup_mocks_for_rspec $rspec_mocks ||= Spec::Mocks::Space.new end def verify_mocks_for_rspec $rspec_mocks.verify_all end def teardown_mocks_for_rspec $rspec_mocks.reset_all end end end end end
This file must require any libraries or resources that implement the framework, and then define a Spec::Plugins::MockFramework module with the following methods:
setup_mocks_for_rspecis called before each example is run.verify_mocks_for_rspecis called after each example is run. Use this if you want RSpec to automatically verify your mocks after each example. You must supply this method either way, but you can leave it empty if your framework doesn’t support auto-verification.teardown_mocks_for_rspecis guaranteed to be run after each example even when there are errors. Use this to ensure that there is no state shared across example, clearing out changes to static resources like class-level mock expectations, etc.
Once you have defined your adapter, you can then tell RSpec to use your adapter like so:
Spec::Runner.configure do |config| config.mock_with '/path/to/my/adapater.rb' end