代码之家  ›  专栏  ›  技术社区  ›  Alex Harvey

使用Helpers模块在Rspec中声明上下文

  •  0
  • Alex Harvey  · 技术社区  · 7 年前

    我试图从Helpers模块中递归地声明Rspec中的上下文。

    (我的代码将以一种不寻常的方式使用这些上下文,即递归地对嵌套哈希中的键进行断言。也许我可以用另一种方法来解决这个问题,但这不是重点。)

    一个最简单完整的例子是:

    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 here . 这似乎使助手在示例中可用,但它不允许我实际声明上下文。)

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alex Harvey    7 年前

    正如评论中所建议的,这里的答案通常是使用共同的例子。因此,我可以将这个代码示例重构为:

    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 .

    推荐文章