Way*_*rad 11 ruby rspec2 ruby-1.9
我怎么能混个模块到一个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
Run Code Online (Sandbox Code Playgroud)
这const_get
当常量的名称不能是有趣的可以检索的常量.是什么导致了rspec的好奇行为?
我使用MRI 1.9.1和rspec 2.8.0.MRI 1.8.7的症状相同.
Joh*_*lla 11
你想要的extend
不是include
.这适用于Ruby 1.9.3,例如:
module Foo
X = 123
end
describe "specs with modules extended" do
extend Foo
p X # => 123
end
Run Code Online (Sandbox Code Playgroud)
或者,如果要在不同测试中重用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
Run Code Online (Sandbox Code Playgroud)
如果要在不同的上下文中重用规范,请使用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
Run Code Online (Sandbox Code Playgroud)
Bra*_*dan 10
您可以使用RSpec shared_context
:
shared_context 'constants' do
FOO = 1
end
describe Model do
include_context 'constants'
p FOO # => 1
end
Run Code Online (Sandbox Code Playgroud)