Alex Rivera | Logout

How to mix a module into an rspec context

Asked 2012-02-04T13:58:24.157
12

How can I mix a module into an rspec context (aka describe), such that the module's constants are available to the spec?

module Foo
  FOO = 1
end

describe 'constants in rspec' do

  include Foo

  p const_get(:FOO)    # => 1
  p FOO                # uninitialized constant FOO (NameError)

end

That const_get can retrieve the constant when the name of the constant cannot is interesting. What's causing rspec's curious behavior?

I am using MRI 1.9.1 and rspec 2.8.0. The symptoms are the same with MRI 1.8.7.

Edit
Report

1 Answer

11

You can use RSpec's shared_context:

shared_context 'constants' do
  FOO = 1
end

describe Model do
  include_context 'constants'

  p FOO    # => 1
end
answered 2012-02-04T14:21:20.197

Your Answer