我有一个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
的错误方法,因此难以测试?我的非工作尝试在这里(从较大的spec文件剪裁)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
答案 0 :(得分:0)
我认为你必须重新加载一个对象。请尝试以下方法:
@organization.products.reload
在before语句中发布产品后。基本上,一旦保存@organization,调用@ organization.products就会有一个force_reload = false。参考:http://guides.rubyonrails.org/association_basics.html#has_many-association-reference
此外,既然你问过,鉴于你已经建立了关系,你实际上应该能够使用产品关系定义你的方法:
def has_product?(prod)
products.include? prod
end
def add_product!(prod)
products << prod
end
我认为如果您以这种方式定义方法,则可能不必重新加载,因为organization.products关联已经更新。
希望有所帮助。