作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
如何将模块混合到 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
可以在常量名称不能检索常量的情况下检索常量,这很有趣。是什么导致了 rspec 的奇怪行为?
我正在使用 MRI 1.9.1 和 rspec 2.8.0。症状同MRI 1.8.7。
最佳答案
你想要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
关于ruby - 如何将模块混合到 rspec 上下文中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9141397/
我是一名优秀的程序员,十分优秀!