我正在从具有JSON夹具的完整JSON数据集中提取字段子集。我能想到的更好的方法如下:
require "spec_helper"
# API ref.: GET /repos/:owner/:repo
# http://developer.github.com/v3/repos/
describe Elasticrepo::RepoSubset do
context "extract a subset of repository fields" do
let(:parsed) { Yajl::Parser.parse(fixture("repository.json").read) }
subject { Elasticrepo::RepoSubset.new(parsed) }
context "#id" do
its(:id) { should eq(2126244) }
end
context "#owner" do
its(:owner) { should eq("twitter") }
end
context "#name" do
its(:name) { should eq("bootstrap") }
end
context "#url" do
its(:url) { should eq("https://api.github.com/repos/twitter/bootstrap") }
end
context "#description" do
its(:description) { should eq("Sleek, intuitive, and powerful front-end framework for faster and easier web development.") }
end
context "#created_at" do
its(:created_at) { should eq("2011-07-29T21:19:00Z") }
end
context "#pushed_at" do
its(:pushed_at) { should eq("2013-04-13T03:56:36Z") }
end
context "#organization" do
its(:organization) { should eq("Organization") }
end
context "#full_name" do
its(:full_name) { should eq("twitter/bootstrap") }
end
context "#language" do
its(:language) { should eq("JavaScript") }
end
context "#updated_at" do
its(:updated_at) { should eq("2013-04-13T19:12:09Z") }
end
end
end
但我想知道是否有更好,更智能,更清洁或更优雅的方式。第一类TDD是这样的:
module Elasticrepo
class RepoSubset
attr_reader :id, :owner, :name, :url, :description, :created_at, :pushed_at,
:organization, :full_name, :language, :updated_at
def initialize(attributes)
@id = attributes["id"]
@owner = attributes["owner"]["login"]
@name = attributes["name"]
@url = attributes["url"]
@description = attributes["description"]
@created_at = attributes["created_at"]
@pushed_at = attributes["pushed_at"]
@organization = attributes["owner"]["type"]
@full_name = attributes["full_name"]
@language = attributes["language"]
@updated_at = attributes["updated_at"]
end
end
end
答案 0 :(得分:2)
我会删除各个上下文块。他们不添加任何其他信息。
答案 1 :(得分:1)
我会使用键/值的映射并迭代,或者使用正确的值创建一个对象并比较整个对象。