首页 文章

在Ruby w / rspec的Cucumber中,我如何期望/断言在Then子句中进行webmocked调用?

提问于
浏览
0

我正在编写一个充当远程API客户端的gem,因此我使用webmock来模拟远程API,使用带有rspec-mock的Cucumber进行测试 .

作为我的Cucumber测试的一部分,我打算在 Given 子句中存根我的API,但后来我想指定在 Then 子句中调用远程API .

一个非常基本的例子是:

Feature file

Scenario: Doing something that triggers a call
  Given I have mocked Google
  When I call my library
  Then it calls my Google stub
  And I get a response back from my library

Step definition

Given /I have mocked my API/ do
  stub_request(:get, 'www.google.com')
end

When /I call my library/ do
  MyLibrary.call_google_for_some_reason
end

Then /it calls my Google stub/ do
  # Somehow test it here
end

The question: 如何验证我的谷歌存根已被调用?

旁注:我知道我可以使用 expect(a_request(...))expect(WebMock).to ... 语法,但我的感觉是我在 Given 子句中定义的'll be repeating what' .

1 回答

  • 1

    我自己回答这个问题,虽然有人确认这是正确的和/或没有重大缺陷是好的:

    Given /I have mocked my API/ do
      @request = stub_request(:get, 'www.google.com')
    end
    
    Then /it calls my Google stub/ do
      expect(@request).to have_been_made.once
    end
    

    需要注意的是 @request 的赋值和 Then 子句中对它的期望 .

    在两个独立场景的有限测试中,这种方法似乎有效 .

相关问题