使用Rspec匹配复杂的数据结构(结构数组)

时间:2012-06-27 17:51:46

标签: ruby-on-rails ruby rspec tdd bdd

如何将以下数组与Rspec匹配?

[#<struct Competitor html_url="https://github.com/assaf/vanity", description="Experiment Driven Development for Ruby", watchers=845, forks=146>, 
 #<struct Competitor html_url="https://github.com/andrew/split", description="Rack Based AB testing framework", watchers=359, forks=43>]

我需要检查一个类方法是否返回一个struct数组,如前一个或更广泛的结构,包括前一个。

更新

我目前正在进行绿色测试,

require 'spec_helper'
  describe "Category" do
    before :each do
      @category = Category.find_by(name: "A/B Testing")
    end

    describe ".find_competitors_by_tags" do
      it "returns a list of competitors for category" do
        competitors = Category.find_competitors_by_tags(@category.tags_array).to_s
        competitors.should match /"Experiment Driven Development for Ruby"/
      end
    end
  end
end

但我想知道这是否是测试以下方法的正确方法,或者您认为它可能更好:

class Category
  ...

  Object.const_set :Competitor, Struct.new(:html_url, :description, :watchers, :forks)
  def self.find_competitors_by_tags(tags_array)
    competitors = []

    User.all_in('watchlists.tags_array' => tags_array.map{|tag|/^#{tag}/i}).only(:watchlists).each do |u|
      u.watchlists.all_in(:tags_array => tags_array.map{|tag|/^#{tag}/i}).desc(:watchers).each do |wl|
        competitors << Competitor.new(wl.html_url, wl.description, wl.watchers, wl.forks)
      end
    end
    return competitors
  end
end

1 个答案:

答案 0 :(得分:3)

我会测试确保您的查找功能正常工作所需的最低要求。您可能不需要为每个字段检查返回的记录。你拥有的是什么。我稍微修改一下,只看一下描述(或其他适当的字段):

  it "returns a list of competitors for category" do
    competitors = Category.find_competitors_by_tags(@category.tags_array)
    descriptions = competitors.map(&:description).sort
    descriptions.should == [
      "Experiment Driven Development for Ruby",
      "Rack Based AB testing framework",
    ]
  end