【问题标题】:Is there a better way to test this Ruby class with RSpec?有没有更好的方法来使用 RSpec 测试这个 Ruby 类?
【发布时间】:2013-04-14 10:37:15
【问题描述】:

我正在从具有 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

【问题讨论】:

    标签: ruby unit-testing testing rspec tdd


    【解决方案1】:

    我会删除各个上下文块。他们不添加任何额外的信息。

    【讨论】:

    • 在一天结束时...,我同意
    【解决方案2】:

    我会使用键/值映射并进行迭代,或者创建具有正确值的对象并比较整个对象。

    【讨论】:

    • 我也喜欢你的方式:模拟一个假的 obj 来比较
    猜你喜欢
    • 1970-01-01
    • 2013-08-18
    • 2012-04-28
    • 2018-02-15
    • 2019-08-26
    • 2014-08-31
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多