gpt4 book ai didi

ruby - 如何将模块混合到 rspec 上下文中

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:18 24 4
gpt4 key购买 nike

如何将模块混合到 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_examplesit_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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com