代码之家  ›  专栏  ›  技术社区  ›  kenji

如何使用来自外部服务的验证来存根模型

  •  1
  • kenji  · 技术社区  · 7 年前

    在这里,我们有一个具有多个验证的客户模型,其中一个验证访问外部服务以验证该人员是否存在。

    在这里,我们测试所有验证:

    describe Customer do
    
       it 'is not valid without a name' do
          customer = build_stubbed(:customer, name: nil)
          customer.valid?
          asserts...
       end
    
       it 'is not valid without a full name' do
          customer = build_stubbed(:customer, name: 'Test')
          customer.valid?
          asserts...
       end
    
       if 'should check if user really exists' do
          customer = build_stubbed(:customer, doc_id: '00000000')
          customer.valid?
          asserts....
       end
    
       other tests...
    

    最后一项使用doc\u id测试外部服务验证,以检查此人是否存在,但在这里,每个测试都会运行所有验证,因此我应该在每个测试之前使用stub\u请求服务请求,还是在每个测试中使用stub\u请求服务请求?

    1 回复  |  直到 7 年前
        1
  •  1
  •   hezanathos    7 年前

    你应该使用 context 指定哪些测试使用stup,哪些不使用。这是建议的 here 例如这样,您将能够拥有一个方法存根的上下文,并在其他上下文中使用外部服务测试验证。