Stubbing WebMock 不拦截请求

Stubbing with WebMock not intercepting request

我正在尝试使用 WebMock 将请求存根到控制器。但是,当我创建存根时,请求并没有按照我期望或希望的方式被拦截。

Controller 除了根据查询参数 JSON 进行渲染之外什么都不做:

def index      
  render json: MyThing.search(params[:query]).as_json(only: [:id], methods: [:name_with_path])
end

存根如下:

mything_val = { ...json values... }
stub_request(:any, mything_path).with(query: { "query" => "a+thing" }).to_return(body: mything_val, status: 200)
page.find('.MyThingInput > input').set('a thing')

# Note: I've tried this with and without the `query:` parameter, as well as 
with and without specifying header info.

这是在触发一个 React 组件。它所做的是,当输入一个或多个单词时,它会向 mything_path 发送一个 AJAX 请求,其中包含输入的值,其中 return 是 JSON 几个关于用户可能意味着什么的建议。这些在 .MyThingInput-wrapper.

中的 li 元素中

在规范文件中,我包括:

require 'support/feature_helper'
require 'support/feature_matchers'
require 'webmock/rspec'
WebMock.disable_net_connect!

然而,当我将文本输入到 React 组件时,实际发生的是,无论 WebMock 存根如何,它都会访问控制器,发出数据库请求,并且由于测试环境的某些限制而失败。我对这应该如何工作的理解是,当向 mything_url 发出请求时,它应该被 WebMock 拦截,这将 return 我预定义的值,并且根本不会击中控制器。

我的猜测是不知何故我在嘲笑错误的 URI,但老实说,此时我真的不确定。感谢任何和所有输入,我很乐意澄清我在这里提出的任何观点。非常感谢!

最终解决我的问题的是删除模型。我曾尝试将 Controller 存根,但 运行 遇到了问题;然而,这段代码起到了作用:

before do
  mything_value = [{ "id" => "fb6135d12-e5d7-4e3r-b1h6-9bhirz48616", "name_with_path" => "New York|USA" }]
  allow(MyThing).to receive(:search).and_return(mything_value.to_json)
end

这样,它仍然会访问控制器,但会打断数据库查询,这是真正的问题,因为它在测试模式下使用了 Elasticsearch(不是 运行。)

我对像这样硬编码 JSON 不太满意,但我尝试了其他几种方法但没有成功。老实说,在这一点上,我只是选择有效的方法。

有趣的是,我在 Infused 的建议之前尝试过这种方法,但语法不太正确;删除 Controller 操作也是如此。上床睡觉,醒来,用我 认为 相同的语法再次尝试,并且成功了。我只是要慢慢后退,感谢代码之神。

如果问题出在弹性搜索上,那么也许可以尝试

  • 正在安装 Webmock
# in your gemfile
group :test do
gem 'webmock'
end
  • 停止对 elasticsearch 的请求并返回 JSON

spec_helper 中的类似内容:

  config.before(:each) do
    WebMock.enable!
    WebMock.stub_request(:get, /#{ELASTICSEARCH_URL}/).to_return(body: File.read('spec/fixtures/elasticsearch/search-res.json'))ELASTICSEARCH_URL
    # and presumably, if you are using elasticsearch-rails, you'd want to stub out the updating as well:
    WebMock.stub_request(:post, /#{ELASTICSEARCH_URL}/).to_return(status: "200")
    WebMock.stub_request(:put, /#{ELASTICSEARCH_URL}/).to_return(status: "200")
    WebMock.stub_request(:delete, /#{ELASTICSEARCH_URL}/).to_return(status: "200")
  end

当然,这会消除对弹性搜索的所有调用,并且 returns 所有答案都相同 JSON。如果您需要为每个查询提供不同的响应,请深入了解 webmock 的文档。