0

试图遵循 demeter 法则,我正在重构代码。目标是让每个模型都有方法,作为其他模型提取数据的 API。

组织有一个实例方法#suppliers_for_purchaser,它返回一个采购员的所有供应商。此方法已在 organization_spec.rb 中成功测试。

Price 有一个类方法 .latest_prices_for_purchaser。此类方法采用一个参数(Organization 的实例)并使用此参数调用 Organization#suppliers_for_purchaser。这会导致RSpec中不存在错误架构:

Failures:

1) Price.latest_prices_for_purchaser returns latest prices for purchaser
 Failure/Error: Price.latest_prices_for_purchaser(purchaser).should have(2).prices
 ActiveRecord::StatementInvalid:
   PG::Error: ERROR:  schema "organization" does not exist
   : SELECT COUNT(*) FROM "organizations" INNER JOIN "partnerships" ON "organizations"."id" = "partnerships"."partner_id" WHERE "partnerships"."organization_id" = 1 AND (organization.organization_role.name = 'supplier')
 # ./spec/models/price_spec.rb:24:in `block (3 levels) in <top (required)>'

模型(简化)

class Organization < ActiveRecord::Base
  # self referencing n:n table
  has_many :partners, :through => :partnerships
  # some more associations, all tested

  # successfully tested in an RSpec unit test for this model
  def suppliers_for_purchaser    
    partners.where('organization.organization_role.name = ?', "supplier")
  end
end

class Price < ActiveRecord::Base
  def self.latest_prices_for_purchaser(purchaser)
    suppliers = purchaser.suppliers_for_purchaser
    # some more code that doesn't get executed because it crashes on the line above
  end
end

price_spec.rb(简化版)

describe Price do
  describe ".latest_prices_for_purchaser" do

    # passes
    it "responds" do
      Price.should respond_to(:latest_prices_for_purchaser)
    end

    it "returns latest prices for purchaser" do
      purchaser = create(:organization_purchaser)
      supplier = create(:organization_supplier)
  partnership = create(:partnership, organization: purchaser, partner: supplier) 
      2.times do
        price = create(:price, created_at: 10.hours.ago, supplier: supplier, purchaser: purchaser)
      end
      Price.latest_prices_for_purchaser(purchaser).should have(2).prices                  
    end

  end
end

更新

cheeseweasel找到了解决方案。单元测试 Price.latest_prices_for_purchaser 仅在将 Organization#suppliers_for_purchaser 更改为:

partners.joins(:organization_role).where('organization_roles.name = ?', "supplier")
4

1 回答 1

1

问题在于suppliers_for_purchaser 方法 - 在构造查询时,您需要显式定义与相关表的任何连接,因此如下:

partners.where('organization.organization_role.name = ?', "supplier")

需要定义组织角色加入:

partners.joins(:organization_role).where('organization_roles.name = ?', "supplier")
于 2013-01-16T09:11:18.190 回答