Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix a module into an rspec context

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.

like image 324
Wayne Conrad Avatar asked Feb 04 '12 13:02

Wayne Conrad


2 Answers

You can use RSpec's shared_context:

shared_context 'constants' do
  FOO = 1
end

describe Model do
  include_context 'constants'

  p FOO    # => 1
end
like image 132
Brandan Avatar answered Nov 11 '22 20:11

Brandan


You want extend, not include. This works in Ruby 1.9.3, for instance:

module Foo
  X = 123
end

describe "specs with modules extended" do
  extend Foo
  p X # => 123
end

Alternatively, if you want to reuse an RSpec context across different tests, use shared_context:

shared_context "with an apple" do
  let(:apple) { Apple.new }
end

describe FruitBasket do
  include_context "with an apple"

  it "should be able to hold apples" do
    expect { subject.add apple }.to change(subject, :size).by(1)
  end
end

If you want to reuse specs across different contexts, use shared_examples and it_behaves_like:

shared_examples "a collection" do
  let(:collection) { described_class.new([7, 2, 4]) }

  context "initialized with 3 items" do
    it "says it has three items" do
      collection.size.should eq(3)
    end
  end
end

describe Array do
  it_behaves_like "a collection"
end

describe Set do
  it_behaves_like "a collection"
end
like image 40
John Feminella Avatar answered Nov 11 '22 19:11

John Feminella