Ruby on rails 在RSpec/Rails中测试数组的预期顺序

Ruby on rails 在RSpec/Rails中测试数组的预期顺序,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,在RSpec规范文件中,我有以下测试 it 'should return 5 players with ratings closest to the current_users rating' do matched_players = User.find(:all, :select => ["*,(abs(rating - current_user.rating)) as player_rating"],

在RSpec规范文件中,我有以下测试

it 'should return 5 players with ratings closest to the current_users rating' do
  matched_players = User.find(:all, 
                              :select => ["*,(abs(rating - current_user.rating)) as player_rating"], 
                              :order => "player_rating", 
                              :limit => 5)

  # test that matched_players array returns what it is suppose to 
end

我如何完成这项工作以测试匹配的玩家是否返回了正确的用户。

我认为您应该首先将一些测试用户引入测试数据库(例如使用工厂),然后查看测试是否返回了正确的用户

另外,在模型中有一个返回匹配用户的方法也更有意义

例如:

describe "Player matching" do
  before(:each) do
    @user1 = FactoryGirl.create(:user, :rating => 5)
    ...
    @user7 = FactoryGirl.create(:user, :rating => 3)
  end

  it 'should return 5 players with ratings closest to the current_users rating' do
    matched_players = User.matched_players
    matched_players.should eql [@user1,@user3,@user4,@user5,@user6]
  end
end
  • 您的模型不应该知道您当前的用户(控制器知道这个概念)
  • 您需要将其提取为用户类上的方法,否则测试它就没有意义了,也就是说,为什么要测试应用程序代码中甚至没有的逻辑
  • 获取匹配玩家的函数不需要知道当前用户或任何用户,只需要知道评级
  • 要测试它,请创建一组用户实例,调用该方法,并查看结果是您期望的正确用户实例的列表
models/user.rb

class User < ActiveRecord::Base
  ...
  def self.matched_players(current_user_rating)
    find(:all,
         select: ["*,(abs(rating - #{current_user_rating)) as match_strength"], 
         order: "match_strength", 
         limit: 5)
  end
  ...
end

如何确定“正确的用户”?确定要匹配的数组并测试它。这个问题的标题可能会有所改进,因为它看起来像一个纯Ruby问题,而实际上这是一个测试问题。
describe User do
  ...
  describe "::matched_players" do
    context "when there are at least 5 users" do
      before do
        10.times.each do |n|
          instance_variable_set "@user#{n}", User.create(rating: n)
        end
      end

      it "returns 5 users whose ratings are closest to the given rating, ordered by closeness" do
        matched_players = described_class.matched_players(4.2)

        matched_players.should == [@user4, @user5, @user3, @user6, @user2]
      end

      context "when multiple players have ratings close to the given rating and are equidistant" do
        # we don't care how 'ties' are broken
        it "returns 5 users whose ratings are closest to the given rating, ordered by closeness" do
          matched_players = described_class.matched_players(4)

          matched_players[0].should == @user4
          matched_players[1,2].should =~ [@user5, @user3]
          matched_players[3,4].should =~ [@user6, @user2]
        end
      end
    end

    context "when there are fewer than 5 players in total" do
      ...
    end
    ...
  end
  ...
end