【发布时间】:2022-11-09 14:38:59
【问题描述】:
我创建了一个简单的 ruby 文件(不是 Rails),我正在尝试测试(使用Rspec)我调用 API 的方法。在测试中,我试图通过WebMock 模拟调用,但它一直给我这个错误:
Requests::FilesManager#display fetches the files from the API
Failure/Error: Requests::FilesManager.new.display
ArgumentError:
wrong number of arguments (given 2, expected 1)
这些文件是:
#run.rb
module Requests
require "httparty"
require 'json'
class FilesManager
include HTTParty
def initialize
end
def display
response = HTTParty.get('https://api.publicapis.org/entries', format: :json)
parsed_response = JSON.parse(response.body)
puts "The secret message was: #{parsed_response["message"]}"
end
end
end
和规范文件:
require 'spec_helper'
require_relative '../run'
RSpec.describe Requests::FilesManager do
describe "#display" do
it 'fetches the files from the API' do
stub_request(:get, "https://api.publicapis.org/entries").
to_return(status: 200, body: "", headers: {})
Requests::FilesManager.new.display
end
end
end
编辑: 所以错误似乎来自以下行:
JSON.parse(response.body)
如果我将其注释掉,它就会消失。那么问题是调用的输出不是json(即使在调用HTTParty 时使用format: :json)。我尝试了其他解决方案,但在制作响应 json 时似乎没有任何效果。它只是一个字符串。
【问题讨论】:
-
问题不在于模拟,而在于这一行:
Requests::MyCLI.new.display_files。Requests::MyCLI是什么样的?它的initialize和display_files方法是如何定义的? -
感谢您的回复。抱歉,我更新了@spickermann 错误。任何想法为什么它失败了?
标签: ruby-on-rails ruby rspec httparty webmock