4

我有一个Organization模型acts_as_nested_set,使用awesome_nested_set

class Organization < ActiveRecord::Base
  acts_as_nested_set
  attr_accessible :name, :location_id, :parent_id

  has_many :org_prod_relationships, dependent: :destroy
  has_many :products, through: :org_prod_relationships

  def has_product?(prod)
    org_prod_relationships.find_by_product_id(prod.id)
  end

  def add_product!(prod)
    org_prod_relationships.create!(product_id: prod.id)
  end

  def publish_product!(prod)
    self.descendants.each do |d|
      d.add_product!(prod)
    end
  end
end

如何在 RSpec 中为 编写测试publish_product!,和/或这是在嵌套集中创建的错误方法org_product_relationships,因此难以测试?我的非工作尝试在这里(从较大的规范文件中剪辑)https://gist.github.com/3911555

编辑:更新以包含错误消息。注意,第 79 行和第 80 行是:

it { should have_product(product) }
its(:products) { should include(product) }

在要点。


Failures:

  1) Organization publishes_product 
     Failure/Error: it { should have_product(product) }
       expected #has_product?(#<Product id: 34, name: "floo powder", created_at: "2012-10-21 14:15:08", updated_at: "2012-10-21 14:15:08", photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil>) to return true, got false
     # ./spec/models/organization_spec.rb:79:in `block (3 levels) in <top (required)>'

  2) Organization publishes_product products 
     Failure/Error: its(:products) { should include(product) }
       expected [] to include #<Product id: 35, name: "floo powder", created_at: "2012-10-21 14:15:08", updated_at: "2012-10-21 14:15:08", photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil>
       Diff:
       @@ -1,2 +1,2 @@
       -[#<Product id: 35, name: "floo powder", created_at: "2012-10-21 14:15:08", updated_at: "2012-10-21 14:15:08", photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil>]
       +[]
     # ./spec/models/organization_spec.rb:80:in `block (3 levels) in <top (required)>'

Finished in 29.93 seconds
184 examples, 2 failures

Failed examples:

rspec ./spec/models/organization_spec.rb:79 # Organization publishes_product 
rspec ./spec/models/organization_spec.rb:80 # Organization publishes_product products
4

1 回答 1

0

我认为你必须重新加载一个对象。尝试以下操作:

@organization.products.reload

在之前的声明中发布产品之后。基本上一旦保存了@organization,调用@organization.products 就会有force_reload=false。参考: http: //guides.rubyonrails.org/association_basics.html#has_many-association-reference

此外,既然你问了,鉴于你已经建立了关系,你实际上应该能够使用 products 关系定义你的方法:

def has_product?(prod)
  products.include? prod
end

def add_product!(prod)
  products << prod
end

我认为如果您以这种方式定义方法,您可能不必重新加载,因为 organization.products 关联已经更新。

希望有帮助。

于 2013-05-02T05:43:18.873 回答