# Gemfile
group :test do
gem 'simplecov', require: false
end
# test/test_helper.rb
require 'simplecov'
SimpleCov.start 'rails' do
add_filter '/channels/'
add_group "Services", "app/services"
end
class ActiveSupport::TestCase
...
parallelize(workers: :number_of_processors) if ENV['CI']
...
end
# test/fixtures/automobile_parts.yml
civic_engine:
automobile: civic
part: engine
corolla_clutch:
automobile: corolla
part: clutch
# test/fixtures/automobiles.yml
civic:
manufacture: honda
name: Civic
year: 2018
corolla:
manufacture: toyota
name: Corolla
year: 1999
# test/fixtures/manufactures.yml
honda:
name: Honda
toyota:
name: Toyota
# test/fixtures/parts.yml
engine:
name: Engine
price: 1000
weight: 500
clutch:
name: Clutch
price: 250
weight: 10
# test/controllers/automobiles_controller_test.rb
setup do
@automobile = automobiles(:civic)
end
test "should create automobile" do
assert_difference('Automobile.count') do
post automobiles_url, params: {
automobile: {
manufacture_id: manufactures(:honda).id,
name: 'Prelude',
year: 2020
}
}
end
assert_redirected_to automobile_url(Automobile.last)
end
# test/controllers/manufactures_controller_test.rb
setup do
@manufacture = manufactures(:honda)
end
test "should create manufacture" do
assert_difference('Manufacture.count') do
post manufactures_url, params: {
manufacture: {
name: 'Mazda'
}
}
end
assert_redirected_to manufacture_url(Manufacture.last)
end
# app/models/manufacture.rb
class Manufacture < ApplicationRecord
has_many :automobiles, dependent: :destroy
end
# app/models/part.rb
class Part < ApplicationRecord
has_many :automobile_parts
has_many :automobiles, through: :automobile_parts
has_many :recalls
end
# app/models/recall.rb
class Recall < ApplicationRecord
belongs_to :part
def number_of_affected_automobiles
part.automobiles.size # + 1
end
end
# test/services/automobiles/calculate_price_test.rb
require 'test_helper'
module Automobiles
class CalculatePriceTest < ActiveSupport::TestCase
setup do
@automobile = automobiles(:civic)
end
test "should calculate 1000.00 correctly" do
service = Automobiles::CalculatePrice.call(@automobile)
assert_equal 1000.00, service
end
test "should calculate 250.00 correctly" do
@automobile.update(parts: [parts(:clutch)])
service = Automobiles::CalculatePrice.call(@automobile)
assert_equal 250.00, service
end
test "should calculate 1250.00 correctly" do
@automobile.update(parts: [parts(:clutch), parts(:engine)])
service = Automobiles::CalculatePrice.call(@automobile)
assert_equal 1250.00, service
end
test "should calculate 0.00 correctly" do
@automobile.update(parts: [])
service = Automobiles::CalculatePrice.call(@automobile)
assert_in_delta 0.00, service, 0.01
end
end
end
# test/models/recall_test.rb
require 'test_helper'
class RecallTest < ActiveSupport::TestCase
setup do
@engine = parts(:engine)
end
test "should return correct number_of_affect_automobiles" do
recall = Recall.new(part: @engine, description: '')
assert_equal 1, recall.number_of_affected_automobiles
end
end