我正在尝试为以下方法编写测试:
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 的新手,因此感谢您的帮助!