为什么“不要在“之前”之类的钩子中使用“期望”?

时间:2019-02-21 13:08:48

标签: rspec rubocop-rspec

标题几乎解释了我的问题。我试图用谷歌搜索,但没有发现任何令人满意的东西。 rubocop-rspec does not allow expect inside before,为什么呢?是否有充分的理由避免这种用法?感谢您的提前解释!

3 个答案:

答案 0 :(得分:0)

仅测试应包括期望(也称为断言)。 before块用于配置运行测试的环境。它们本身并不是要进行测试。

答案 1 :(得分:0)

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

test do
  setup
  exercise
  verify
  teardown
end

beforesetup阶段的一部分,开发人员在其中创建方案和支持数据。

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

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

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
也可以将

before块添加到应用程序的其他层中(spec_helper.rb,共享示例),并且一个人不希望依赖before块的正确顺序来进行测试。成功。

答案 2 :(得分:0)

我同意import React from 'react'; import { NextPage, NextPageContext } from 'next'; import Layout from '@layouts/index'; import { AuthStore, AuthStoreProps } from '@src/stores'; interface HomeProps { cookie?: string; } const HomeController: NextPage<HomeProps> = ({ cookie }) => { const authStore = React.useContext<AuthStoreProps>(AuthStore); const isAuthorized = authStore.getAuthentication(cookie); return <Layout>Home</Layout>; }; HomeController.getInitialProps = async ({ req }: NextPageContext) => { const cookie = req ? req.headers.cookie : ''; return { cookie }; }; export default HomeController; 过滤器中的期望值,因为您没有在示例中进行任何更改,您始终在测试常规设置,但是在before过滤器中,我看不出避免期望值的原因。

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

请参见以下示例:

after

相反
 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

因此,老实说,我不会把这警察当作福音,我认为这与良好的测试做法背道而驰。