Luca G. Soave
Luca G. Soave

Reputation: 12679

Rspec's include matcher, beetwen Hash and String objects

How can I check with Rspec, if all the fields in a Hash object :

{"id"=>5392501, "owner"=>"cainlevy", "name"=>"photor", "url"=>"https://api.github.com/repos/cainlevy/photor", "description"=>"Photo Organizer (in Ruby)", "created_at"=>"2012-08-12T22:26:08Z", "pushed_at"=>"2013-02-19T03:11:10Z", "organization"=>"User", "full_name"=>"cainlevy/photor", "language"=>"Ruby", "updated_at"=>"2013-03-13T02:05:33Z"}

are INCLUDED in a superset of filds which is a String object :

{"id":5392501,"name":"photor","full_name":"cainlevy/photor","owner":{"login":"cainlevy","id":4449,"avatar_url":"https://secure.gravatar.com/avatar/2573ddee29779e76b7da7d3c2c9ff18d?d=https://a248.e.akamai.net},"private":false,"html_url":"https://github.com/cainlevy/photor","description":"Photo Organizer (in Ruby)","fork":false,"created_at":"2012-08-12T22:26:08Z","updated_at":"2013-03-13T02:05:33Z","pushed_at":"2013-02-19T03:11:10Z","git_url":"git://github.com/cainlevy/photor.git","ssh_url":"[email protected]:cainlevy/photor.git","clone_url":"https://github.com/cainlevy/photor.git","svn_url":"https://github.com/cainlevy/photor","homepage":null,"size":312,"watchers_count":4,"language":"Ruby","has_issues":true,"has_downloads":true,"has_wiki":true,"forks_count":0,"mirror_url":null,"open_issues_count":0,"forks":0,"open_issues":0,"watchers":4,"master_branch":"master","default_branch":"master"}

currently I'm going with fixture_repos[0].to_json.should include compared where

fixture_repos[0].to_json.class: String 

and

compared.class: Hash 

and I get the following Failures:

no implicit conversion of Hash into String

which apparently I can't get rid off by conferting string to hash :

fixture_repos[0].to_json.to_h

or vice versa

compared.to_s

UPDATE, here it is the full spec:

require "spec_helper"
  describe Elasticrepo::Extractor do
    let(:fixture_repos)  { Yajl::Parser.parse(fixture("repositories.json").read) }

    context "GET /users/:user/starred" do
      describe "#extract" do 
          let(:compared ) {Yajl::Parser.parse(fixture("live_extracted.repos[0].to_json").read) }

          it "includes compared fields" do
            fixture_repos[0].to_json.should include compared
          end
      end
    end 
  end 
end

Upvotes: 2

Views: 1302

Answers (1)

Mark Thomas
Mark Thomas

Reputation: 37517

You can't compare a Hash with a String. But it's not really a String, is it? It's a JSON object. You can compare JSON objects.

Since you're using rspec, I'd recommend json_spec. It has an include_json matcher which should solve your problem. It has other matchers you might find useful as well.

Upvotes: 2

Related Questions