2

如果哈希对象中的所有字段,我如何检查 Rspec:

{"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"}

包含在作为字符串对象的字段超集中

{"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":"git@github.com: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"}

目前我要去fixture_repos[0].to_json.should include compared哪里

fixture_repos[0].to_json.class: String 

compared.class: Hash 

我得到以下失败:

no implicit conversion of Hash into String

显然我无法通过将字符串赋予 hash 来摆脱它:

fixture_repos[0].to_json.to_h

或相反亦然

compared.to_s

更新,这里是完整的规范:

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
4

1 回答 1

2

您无法将哈希与字符串进行比较。但它不是真正的字符串,是吗?它是一个 JSON 对象。您可以比较 JSON 对象。

由于您使用的是 rspec,我建议您使用json_spec。它有一个include_json匹配器,可以解决你的问题。它还有其他你可能会觉得有用的匹配器。

于 2013-04-23T16:01:34.153 回答