我有一个简单的Sinatra,端点为"/status",它返回一个看起来像这样的JSON:
curl http://localhost
{"stats":{"hostname":"Home","cpu":null,"disk":null,"ram":null,"check_time":null}}
我正在尝试在 RSpec 中编写测试,以测试应用程序是否响应此端点以及端点是否以正确的格式返回正确的数据。终结点如下所示:
class App < Sinatra::Base
@@stat = Stat.new
def self.stat
@@stat
end
get '/status' do
{ stats: @@stat.to_h }.to_json
end
end
统计类如下所示:
class Stat
attr_accessor :hostname, :cpu, :disk, :ram, :check_time
@@stat = []
def initialize(attributes = {})
hostname = `hostname`.strip
@hostname = hostname
@cpu = attributes[:cpu]
@disk = attributes[:disk]
@ram = attributes[:ram]
@check_time = attributes[:check_time]
end
def to_h
{
hostname: hostname,
cpu: cpu,
disk: disk,
ram: ram,
check_time: check_time
}
end
end
当我这样做curl http://localhost
时,它会返回以下内容:
{"stats":{"hostname":"Home","cpu":null,"disk":null,"ram":null,"check_time":null}}
我在测试中遇到问题,我期望这种格式,但得到其他东西:
describe "GET /status" do
let(:response) { get "/status" }
it "returns proper JSON" do
expect(response.body).to eq({"stats":{"hostname":"Home","cpu":null,"disk":null,"ram":null,"check_time":null}})
end
end
首先,它不喜欢null
(尽管curl
命令返回null
(。如果我将其更改为nil
,则得到以下结果:
expected: {:stats=>{:hostname=>"Home", :cpu=>nil, :disk=>nil, :ram=>nil, :check_time=>nil}}
got: "{"stats":{"hostname":"Home","cpu":null,"disk":null,"ram":null,"check_time":null}}"
当我这样做时 puts response.body
我得到这个:
{"stats":{"hostname":"Home","cpu":null,"disk":null,"ram":null,"check_time":null}}
我该如何解决这个问题?抱歉,如果这个问题对某些人来说似乎不合适,但我仍然学习使用 RSpec 进行测试。提前谢谢你
你对JSON响应和Ruby的哈希感到困惑。您的 api 返回 json,在测试中,您必须比较两个 json 字符串或两个哈希。例如,要使用 json 进行比较,您可以执行以下操作:
expect(response.body).to eq({ stats: { hostname: "Home", cpu: nil, disk: nil, ram: nil, check_time: nil } }.to_json)
或者使用哈希:
expect(JSON.parse(response.body)).to eq({ "stats" => { "hostname" => "Home", "cpu" => nil, "disk" => nil, "ram" => nil, "check_time" => nil } })