如何在RSPEC中使用相同名称的变量传递?

发布于 2025-01-31 01:40:24 字数 512 浏览 2 评论 0原文

让我们想象我有一些测试,想使用共享的示例,例如:

RSpec.shared_examples "shared examples" do
  let(:x) { "" }
  
  it "should be equal to 5" do
    expect(x).to eq(5)
  end
end

然后使用它:

  describe "my tests" do
    let(:x) { 5 }

    it_behaves_like "shared examples" do
      let(:x) { x }
    end
  end

我知道我可以隐式地做到这一点,而无需传递let(:x){x){x} 块,一切都会起作用。但是我要实现的目标是为我的测试增加更加清晰度。

因此,问题是:如何通过相同名称传递变量(如果需要的话),而不会陷入最大呼叫堆栈错误到子共享示例块中?

请让我知道我的方法一般不正确。

Let's imagine I have some tests and want to use shared examples, e.g.:

RSpec.shared_examples "shared examples" do
  let(:x) { "" }
  
  it "should be equal to 5" do
    expect(x).to eq(5)
  end
end

and then use it like:

  describe "my tests" do
    let(:x) { 5 }

    it_behaves_like "shared examples" do
      let(:x) { x }
    end
  end

I know that I can do that implicitly, without passing let(:x) { x } to the child block and everything will work. But what I'm trying to achieve - is to add more clarity to my tests.

So the question is: how to pass a variable (override if you want) with the same name without falling into maximum call stack error to a child shared examples block?

Please let me know if my approach is not right in general.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴我老 2025-02-07 01:40:24

您只需要定义变量内部块,let是懒惰的,因此直到第一次才能对其进行评估
它定义的方法是被调用的,但是它们需要在上下文之类的内部块中,类似的内容:

RSpec.describes "shared examples" do  

  context 'when x has value' do
    let(:x) { 5 }

    it "should be equal to 5" do
      expect(x).to eq(5)
    end
  end

  context 'when x is empty' do
    let(:x) { '' }

    it "should be empty" do
      expect(x).to eq('')
    end
  end
end

You just need to define the variable inside blocks, let is lazy-evaluated, so it is not evaluated until the first time
the method it defines is invoked, but they need to be inside blocks like context, something like this:

RSpec.describes "shared examples" do  

  context 'when x has value' do
    let(:x) { 5 }

    it "should be equal to 5" do
      expect(x).to eq(5)
    end
  end

  context 'when x is empty' do
    let(:x) { '' }

    it "should be empty" do
      expect(x).to eq('')
    end
  end
end

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文