I am working with Spree gem and Rails 6. I create decorator for Spree::Variant and Spree::Product
variant_decorator.rb:
# frozen_string_literal: true
module Spree
module VariantDecorator
def display_price_ca(currency = Spree::Config[:currency])
price_in(currency, Spree::Country.ca)&.display_price
end
def display_price_us(currency = Spree::Config[:currency])
price_in(currency, Spree::Country.us)&.display_price
end
def price_in(currency, country = nil)
pricess = prices.select { |price| price.currency == currency } || prices.build(currency: currency)
return pricess.last unless country
pricess.sort_by { |e| -e[:id] }
.find { |p| p.country == country }
end
def amount_in(currency, country = nil)
price_in(currency, country).try(:amount)
end
end
end
Spree::Variant.prepend Spree::VariantDecorator
product_decorator.rb
# frozen_string_literal: true
module Spree
module ProductDecorator
module ClassMethods
def really_destroy_all
ClassMethodWorker
.perform_async(klass: 'Spree::Product',
instance_id: Spree::Product.unscoped.pluck(:id),
metod: 'really_destroy!')
end
def discontinue_on_now!
unscoped.update_all(discontinue_on: DateTime.current)
end
end
def self.prepended(base)
class << base
prepend ClassMethods
end
base.validates :price_list_material_id, uniqueness: true
base.has_many :prices, through: :master
base.has_many :countries, through: :prices
base.delegate :display_price_ca, :display_price_us, to: :find_or_build_master
end
end
end
Spree::Product.prepend Spree::ProductDecorator
I create simple Rspec for display_price_ca and display_price_us
describe Spree::Product, type: :model do
context 'product instance' do
context 'prices' do
let(:product_ca) { create(:product_ca, country_price: 15) }
let(:product_us) { create(:product_us, country_price: 25) }
let(:product_all_country) { create(:product_all_country) }
it '#display_price_ca' do
expect(product_ca.display_price_ca.to_s).to eq('$15.00')
expect(product_all_country.display_price_ca.to_s).to eq('$20.00')
end
it '#display_price_us' do
expect(product_us.display_price_us.to_s).to eq('$25.00')
expect(product_all_country.display_price_us.to_s).to eq('$10.00')
end
end
end
end
SimpleCov not handle decorators and show to me:
Coverage report generated for RSpec to /data/server-store/coverage. 163 / 1387 LOC (11.75%) covered
I have SimpeCov start in spec_hepler.rb:
require 'simplecov'
SimpleCov.start "rails"
Result for variant_decorator.rb
:
I see lines not covered, but it should be covered. What might be a problem and how to fix it? Thanks.
You mentioned that you added the SimpleCov call to
spec_helper.rb
. If you also have arails_helper.rb
file, and you require that file from your specs, you will need to add the SimpleCov initialization to that file instead. Add it to the very top of the file, before anything else, otherwise your decorator files will not be included.I'm working on a large Spree-based application and I also ran into this problem.