首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么不在`before`这样的钩子中使用`expect`?

为什么不在`before`这样的钩子中使用`expect`?
EN

Stack Overflow用户
提问于 2019-02-21 21:08:48
回答 3查看 1.4K关注 0票数 2

我的问题很大程度上是通过标题来解释的。我试着在谷歌上搜索,但没有找到任何令人满意的东西。rubocop-rspec does not allow expect inside before,为什么?有没有一个好的理由来避免这样的用法?感谢您的提前解释!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-01 21:57:05

Four phase test是一种通常用于单元测试的测试模式。它的一般形式:

代码语言:javascript
复制
test do
  setup
  exercise
  verify
  teardown
end

beforesetup阶段的一部分,开发人员在该阶段创建场景和支持数据。

expectverify阶段的一部分,该阶段发生在it块中。

例如,一种常见的模式是在before块中使用allow,在it块中使用expect

代码语言:javascript
复制
RSpec.describe User do
  describe '#forgot_password' do
    before { allow(EmailService).to receive(:send) }

    subject { FactoryBot.create(:user).forgot_password }

    it 'sends an email to user to start the password resetting process' do
      subject
      expect(EmailService).to have_received(:send).with(...)
    end
  end
end

还可以在应用程序的其他层(spec_helper.rb,共享示例)中添加before块,人们不希望为了测试成功而依赖于before块的正确顺序。

票数 2
EN

Stack Overflow用户

发布于 2019-02-28 18:42:46

只有测试应该包含期望(也称为断言)。before块用于配置运行测试的环境。它们本身并不意味着是测试。

票数 1
EN

Stack Overflow用户

发布于 2019-11-20 18:37:06

我同意before过滤器中的期望,因为您在示例中没有改变任何东西,您总是在测试常规设置,但是在after过滤器中,我没有看到避免期望的理由。

在编写测试时,上下文是最重要的,您在不同的参数(或上下文)下测试相同的代码,因此,示例只需要修改上下文,断言可以保持不变。

请参阅此示例:

代码语言:javascript
复制
 RSpec.describe Foo do
  subject { create(:foo) }

  describe 'some_method' do
    let(:foo) { create(:foo) }

    after do
      foo.update_rate
      subject.update_rate

      expect(foo.rate).to be > subject.rate
    end

    it 'gives higher rates to foos with more reviews if all are positive' do
      foo.update!(votes_up_count: 10, reviews_count: 10)
      subject.update!(votes_up_count: 1, reviews_count: 1)
    end

    it 'gives higher rates to foos with less positive reviews and no negative reviews' do
      foo.update!(votes_up_count: 4, reviews_count: 4)
      subject.update!(votes_up_count: 5, reviews_count: 6)
    end
  end
end

而不是

代码语言:javascript
复制
 RSpec.describe Foo do
  subject { create(:foo) }

  describe 'some_method' do
    let(:foo) { create(:foo) }

    it 'gives higher rates to foos with more reviews if all are positive' do
      foo.update!(votes_up_count: 10, reviews_count: 10)
      subject.update!(votes_up_count: 1, reviews_count: 1)

      foo.update_rate
      subject.update_rate

      expect(foo.rate).to be > subject.rate
    end

    it 'gives higher rates to foos with less positive reviews and no negative reviews' do
      foo.update!(votes_up_count: 4, reviews_count: 4)
      subject.update!(votes_up_count: 5, reviews_count: 6)

      foo.update_rate
      subject.update_rate

      expect(foo.rate).to be > subject.rate
    end
  end
end

所以老实说,我不会把这个警察当做福音,我认为它违背了良好的测试实践。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54807896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档