我有一个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