如何将模块混合到rspec上下文(又名describe
)中,以便模块的常量可用于规范?
module Foo
FOO = 1
end
describe 'constants in rspec' do
include Foo
p const_get(:FOO) # => 1
p FOO # uninitialized constant FOO (NameError)
end
const_get
可以在常量名称不感兴趣时检索常量。是什么造成了斯科特的奇怪行为?
我正在使用MRI 1.9.1和rspec 2.8.0。 MRI 1.8.7的症状相同。
答案 0 :(得分:11)
您需要extend
,而不是include
。这适用于Ruby 1.9.3,例如:
module Foo
X = 123
end
describe "specs with modules extended" do
extend Foo
p X # => 123
end
或者,如果要在不同测试中重用RSpec上下文,请使用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
如果您想在不同的上下文中重复使用规范,请使用shared_examples
和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
答案 1 :(得分:10)
您可以使用RSpec的shared_context
:
shared_context 'constants' do
FOO = 1
end
describe Model do
include_context 'constants'
p FOO # => 1
end