RSpec:从另一个模型中的方法调用一个模型中的方法时,“模式不存在”

时间:2013-01-16 07:20:42

标签: ruby-on-rails ruby-on-rails-3 rspec rspec2 rspec-rails

试图遵循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(simlified)

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")

1 个答案:

答案 0 :(得分:1)

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

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

需要定义organization_role连接:

partners.joins(:organization_role).where('organization_roles.name = ?', "supplier")
相关问题