2013-06-20 78 views
2

預期的順序在RSpec的規範文件,我有以下的測試測試數組中的RSpec/Rails的

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被返回正確的用戶。

+0

如何確定 「正確的用戶」?確定你想要匹配的數組並測試它。 – vgoff

+0

這個問題的標題可能可以改進,因爲它看起來像一個純粹的Ruby問題,實際上這是一個測試問題。 – joscas

回答

1
  • 您的模型不應該知道你的當前用戶(控制器知道這個概念)
  • 你需要提取,否則,這個是User類的方法測試它沒有意義,即爲什麼測試邏輯甚至不在您的應用程序代碼中?
  • 獲取匹配球員的函數並不需要知道當前用戶或任何用戶的相關信息,僅僅是評級。
  • 要測試它,請創建一堆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 
4

我想你應該首先向測試數據庫引入一些測試用戶(例如使用Factory),然後看到測試返回了正確的測試用戶。

此外,在您的模型中有一個可以返回匹配用戶的方法會更有意義。

例如:

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