How to mix a module into an rspec context

时光怂恿深爱的人放手 提交于 2020-01-22 05:51:19

问题


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.


回答1:


You can use RSpec's shared_context:

shared_context 'constants' do
  FOO = 1
end

describe Model do
  include_context 'constants'

  p FOO    # => 1
end



回答2:


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


来源:https://stackoverflow.com/questions/9141397/how-to-mix-a-module-into-an-rspec-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!