-
-
Save manuelmeurer/8c9f5fc146d7801d51bb to your computer and use it in GitHub Desktop.
Unit test - average_rating
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Product < ActiveRecord::Base | |
has_many :orders | |
has_many :comments | |
def average_rating | |
comments.average(:rating).to_f | |
end | |
validates :name, presence: true | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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