我正在尝试从Helpers模块中在Rspec中递归声明上下文。
(我的代码将以一种不寻常的方式使用这些上下文,即以递归方式对嵌套的Hash中的键进行断言。也许我可以通过其他方式解决此问题,但这不重要。)
一个最小的完整示例是:
module Helpers
def context_bar
context "bar" do
it "baz" do
expect(true).to be true
end
end
end
end
include Helpers
describe "foo" do
Helpers.context_bar
end
如果我现在在Rspec中执行此代码,它将失败并显示:
RuntimeError:
Creating an isolated context from within a context is not allowed. Change `RSpec.context` to `context` or move this to a top-level scope.
然后我可以这样重构它:
def context_bar
context "bar" do
it "baz" do
expect(true).to be true
end
end
end
describe "foo" do
context_bar
end
这对我来说很好,尽管我失去了在模块名称空间中使用此方法和类似方法所带来的可读性。
我有什么办法做这项工作吗?
(请注意,此问题与this这样的问题或Rspec文档here中的问题有表面上的相似之处。这似乎使Helper在示例中可用,但不允许我实际上要声明一个上下文。)
答案 0 :(得分:0)
如评论中所建议,此处的答案通常是使用共享示例。因此,我可以将此代码示例重构为:
RSpec.shared_examples "context_bar" do
context "bar" do
it "baz" do
expect(true).to be true
end
end
end
describe "foo" do
include_examples "context_bar"
end
但是,如果我声明了递归“函数”,例如:
RSpec.shared_examples "compare" do |ref1, ref2|
...
end
并使用:
include_examples "compare", ref1, ref2
此操作失败,并显示以下信息:
ArgumentError:
can't include shared examples recursively
另请参见docs中的共享示例。
在评论中还建议我可以使用自定义匹配器。确实,有人做了非常类似的here。