Skip to content

Instantly share code, notes, and snippets.

@manuelmeurer
Forked from AttyC/product.rb
Last active September 6, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuelmeurer/8c9f5fc146d7801d51bb to your computer and use it in GitHub Desktop.
Save manuelmeurer/8c9f5fc146d7801d51bb 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" do #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
end
#context 2, test 2
context "when the product has comments" do # create context
before do # before running the test...
@product = Product.create
@product.comments.new(rating: 1)
@product.comments.new(rating: 3)
@product.comments.new(rating: 5)
end
it 'returns the average rating of all comments' do
expect(@product.average_rating).to eq 3
end
end
#context 3, test 3
context "when one of the product's comments does not have a rating" do
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 #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