简体   繁体   中英

Failed testing a hash with rspec-rails

I'm building a simple API and one of the features is the fact it must inform the users its version. Then I have a Api controller with a version method

class ApiController < ApplicationController
  def version
    render :json => {version: '0.0.1'}
  end
end

and I also have a route in my config/routes.rb

Rails.application.routes.draw do
  root 'site#index'
  get 'api/version'
end

I'm using Rspec and this is the my failing test

it 'returns the correct version number (0.0.1 by now)' do
  get :version
  expect(response.body).to eq({'version':'0.0.1'})
end

It happens that my test fails ( 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\"}"

What is the point here? Should I test against response.body.to_s or something like that?

It seems I'm missing some point, probably an easy one.

response.body returns a serialized json string whereas {'version':'0.0.1'} is a Hash .

Your expectation should be expect(response.body).to eq({'version':'0.0.1'}.to_json)

or

expect(JSON.parse(response.body)).to eq({'version':'0.0.1'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM