- 你的模型不应该知道你当前的用户(控制器知道这个概念)
- 您需要将其提取为 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