- 您的模型不應該知道你的當前用戶(控制器知道這個概念)
- 你需要提取,否則,這個是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
如何確定 「正確的用戶」?確定你想要匹配的數組並測試它。 – vgoff
這個問題的標題可能可以改進,因爲它看起來像一個純粹的Ruby問題,實際上這是一個測試問題。 – joscas