RSpec Stub 不覆盖多个嵌套的描述块

发布于 2024-12-19 20:02:17 字数 867 浏览 1 评论 0原文

我有一个结构如下的测试套件:

describe ... do
  [list of dates].each do
    describe
      before(:all) do
        base_date = ...
      end
      describe ... do
        [list of times].each do
          describe ... do
            before(:all) do
              base_time = base_date + ...
              DateTime.stub!(:now).and_return(base_time)
            end
            describe ... do
              <test using records within date-time range based on base_time>
            end
            describe ... do
              <another test using records within date-time range based on base_time>
            end
          end
        end
      end
    end
  end
end

第一个测试具有 DateTime(now) == base_time,但第二个测试为 DateTime(now) == 我计算机的日期时间,表明存根不再有效。将 stub! 调用移动到每个 describe 循环中可以解决该问题,但我想了解为什么它不能按编写的方式工作。

I have a test suite structured as follows:

describe ... do
  [list of dates].each do
    describe
      before(:all) do
        base_date = ...
      end
      describe ... do
        [list of times].each do
          describe ... do
            before(:all) do
              base_time = base_date + ...
              DateTime.stub!(:now).and_return(base_time)
            end
            describe ... do
              <test using records within date-time range based on base_time>
            end
            describe ... do
              <another test using records within date-time range based on base_time>
            end
          end
        end
      end
    end
  end
end

The first test has DateTime(now) == base_time, but the second test as DateTime(now) == my computer's date-time, indicating that the stub is no longer in effect. Moving the stub! call into each describe loop resolves the problem, but I would like to understand why it doesn't work as written.

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

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

发布评论

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

评论(1

半夏半凉 2024-12-26 20:02:17

原因可能在于其他地方,存根与多个嵌套描述块一起工作得很好。也许 :all 与 :each 是问题所在: before(:all) 在所有描述块执行之前执行一次,而 before(:each) 每次执行之前执行描述块。

或者可能与存根 DateTime 有关,您尝试过吗

DateTime.any_instance.stub(:now).and_return(base_time)

The reason lies probably elsewhere, stubs work fine with multiple nested describe blocks. Maybe :all vs :each is the problem: before(:all) is executed once before all describe blocks are executed, while before(:each) is executed each time before a describe block is executed.

Or maybe it has something to do with stubbing DateTime, have you tried

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