Skip to content

Instantly share code, notes, and snippets.

@AttyC
Last active September 5, 2015 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AttyC/e4a97821de5c3ec7829b to your computer and use it in GitHub Desktop.
Save AttyC/e4a97821de5c3ec7829b to your computer and use it in GitHub Desktop.
Unit test - average_rating
class Product < ActiveRecord::Base
has_many :orders
has_many :comments
def average_rating
comments.average(:rating).to_f
end
validates :name, presence: true
end
require 'rails_helper' # also requires spec_helper and adds other stuff - if didnt need Rails just use spec_helper but unlikely
describe Product do
describe "#average_rating" do # - the '#' signifies that we are testing an instance method - describe the method you will be testing (which belongs to the Class)
#context 1, test 1
context "when the product doesn't have any comments" #create a context to test
before do # before running the test...
@product = Product.new # ...set up a new instance - this one has no attributes, therefore no comments are present
end
it 'returns 0.0' do # it refers to the instance just created. Describe what you are testing for.
expect(@product.average_rating).to eq 0.0
end
#context 2, test 2
context "when the product has comments" # create context
before do # before running the test...
@product = Product.new
@product.comments.create(rating: 1)
@product.comments.create(rating: 3)
@product.comments.create(rating: 5)
end
it 'returns the average rating of all comments' do
expect(@product.average_rating).to eq 3
end
#context 3, test 3
context "when one of the product's comments does not have a rating"
before do
@product = Product.new
@product.comments.new(rating: '')
end
it 'returns 0.0' do
expect(@product.average_rating).to eq 0.0
end
end #end describe #average_rating
end #end describe Product
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment