gpt4 book ai didi

ruby-on-rails - 平均评级法的 Rspec 模型测试

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:47 25 4
gpt4 key购买 nike

我正在尝试为以下方法编写测试:

def average_rating
reviews = self.reviews
review_sum = reviews.inject(0) { |sum, review| sum += review.rating }
avg_rating = (review_sum / reviews.count).to_i unless review_sum == 0
end

这是我目前所拥有的:

describe "#average_rating" do
it "should be nil when there are no reviews" do
api_without_reviews = Api.new name: 'Fake API', description: 'It does something', category: 'Fake category', url: 'http://www.example.com'
api_without_reviews.average_rating.should be_nil
end
it "should calculate average rating properly" do
api_with_reviews = Api.new name: 'Fake API', description: 'It does something', category: 'Fake category', url: 'http://www.example.com'
api_with_reviews.save
api_with_reviews.reviews.create rating: Random.rand(1..5), thoughts: 'blah'
api_with_reviews.reviews.create rating: Random.rand(1..5), thoughts: 'blah'
average = api_with_reviews.reviews.inject(0) { |sum, review| sum += review.rating } / api_with_reviews.reviews.count
api_with_reviews.average_rating.should eq average
end

结束

如何测试 review_sum 变量是否正确计算总和,或者该方法是否已经过全面测试?我是 rspec 的新手,非常感谢您的帮助!

最佳答案

要直接回答我建议你不要:

  • 生成评论评分的随机值
  • 直接复制方法代码进行验证。你不能给自己的论文打分,不是吗?

相反:

  • 使用手动创建的评分并手动计算平均值
  • 验证该方法是否可以输出您计算的结果。

进一步改进

  • 使用 FactoryGirl 创建测试对象。<​​/li>
  • 擦干代码

我的版本(假设安装了 FactoryGirl)

describe "API" do
describe "average_rating" do
# Use "before" but not "let" because this var must be clean in every example
before { @api = FactoryGirl.create(:api) }

it "should be nil when there are no reviews" do
@api.average_rating.should be_nil
end

it "should calculate average rating properly" do
[1, 5].each do |r|
FactoryGirl.create(:review, rating: r, api: @api)
end
@api.average_rating.should eq(3)
end
end
end

# spec/factories.rb
FactoryGirl.define do
factory :api do
name 'Fake API'
description 'It does something'
category 'Fake category'
url 'http://www.example.com'
end

factory :review do
rating rand(1..5)
thoughts "blah"
api #Association: belongs_to API
end
end

关于ruby-on-rails - 平均评级法的 Rspec 模型测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com