【问题标题】:Rspec's include matcher, beetwen Hash and String objectsRspec 包括 matcher、beetwen Hash 和 String 对象
【发布时间】:2013-04-16 22:25:35
【问题描述】:

如果哈希对象中的所有字段,我如何使用 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

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

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

【问题讨论】:

    标签: ruby json unit-testing testing rspec


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多