1

我正在使用 Spree gem 和 Rails 6。我为 Spree::Variant 和 Spree::Product 创建装饰器

变体装饰器.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

我为display_price_cadisplay_price_us创建了简单的 Rspec

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 不处理装饰器并向我展示:

Coverage report generated for RSpec to /data/server-store/coverage. 163 / 1387 LOC (11.75%) covered

我在 spec_hepler.rb 中启动了 SimpeCov:

require 'simplecov'
SimpleCov.start "rails"

结果variant_decorator.rbSimpleCov 报告

我看到行没有被覆盖,但它应该被覆盖。可能是什么问题以及如何解决?谢谢。

4

1 回答 1

0

您提到您将 SimpleCov 调用添加到spec_helper.rb. 如果您还有一个rails_helper.rb文件,并且您在规范中需要该文件,则需要将 SimpleCov 初始化添加到该文件中。将它添加到文件的最顶部,在其他任何内容之前,否则您的装饰器文件将不会被包含在内。

我正在开发一个基于 Spree 的大型应用程序,我也遇到了这个问题。

于 2021-02-26T14:11:15.950 回答