[英]Failed testing a hash with rspec-rails
我正在構建一個簡單的API,其功能之一就是必須將其版本告知用戶。 然后我有一個帶有版本方法的Api控制器
class ApiController < ApplicationController
def version
render :json => {version: '0.0.1'}
end
end
而且我的config / routes.rb中也有一條路由
Rails.application.routes.draw do
root 'site#index'
get 'api/version'
end
我正在使用Rspec,這是我失敗的測試
it 'returns the correct version number (0.0.1 by now)' do
get :version
expect(response.body).to eq({'version':'0.0.1'})
end
碰巧我的測試失敗( http://imgur.com/7MPL8RO )
1) ApiController GET #version returns the correct version number (0.0.1 by now)
Failure/Error: expect(response.body).to eq(a)
expected: {:version=>"0.0.1"}
got: "{\"version\":\"0.0.1\"}"
這里有什么意義? 我應該測試response.body.to_s還是類似的東西?
似乎我遺漏了一點,可能很簡單。
response.body
返回一個序列化的json字符串,而{'version':'0.0.1'}
是一個Hash
。
您的期望應該是expect(response.body).to eq({'version':'0.0.1'}.to_json)
要么
expect(JSON.parse(response.body)).to eq({'version':'0.0.1'})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.