4

在 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

我将如何完成此操作以测试matched_players 是否返回了正确的用户。

4

2 回答 2

4

我认为您应该首先将一些测试用户介绍给测试数据库(例如使用工厂),然后查看测试返回正确的用户。

此外,在您的模型中有一个返回匹配用户的方法会更有意义。

例如:

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
于 2013-06-20T09:04:22.663 回答
1
  • 你的模型不应该知道你当前的用户(控制器知道这个概念)
  • 您需要将其提取为 User 类上的方法,否则测试它没有意义,即为什么要测试甚至不在您的应用程序代码中的逻辑?
  • 获取匹配玩家的功能不需要知道当前用户或任何用户,只需要知道评分。
  • 要对其进行测试,请创建一堆 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

规格/模型/user_spec.rb

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
于 2013-06-20T09:54:58.803 回答