注意:一个企业有很多目录和产品,一个目录有很多产品。关联已正确定义,它们在应用程序前端中工作。但我无法使此测试通过。我正在使用friendly_id所以你会看到我在某些查找方法上使用@model.slug
我正在尝试这个测试:
describe "GET 'show'" do
before do
@business = FactoryGirl.create(:business)
@catalog = FactoryGirl.create(:catalog, :business=>@business)
@product1 = FactoryGirl.create(:product, :business=>@business, :catalog=>@catalog)
@product2 = FactoryGirl.create(:product, :business=>@business, :catalog=>@catalog)
end
def do_show
get :show, :business_id=>@business.slug, :id=>@catalog.slug
end
it "should show products" do
@catalog.should_receive(:products).and_return([@product1, @product2])
do_show
end
end
使用此工厂(请注意,业务和目录工厂是在其他地方定义的,它们是关联):
FactoryGirl.define do
sequence :name do |n|
"product#{n}"
end
sequence :description do |n|
"This is description #{n}"
end
factory :product do
name
description
business
catalog
end
end
通过此显示操作:
def show
@business = Business.find(params[:business_id])
@catalog = @business.catalogs.find(params[:id])
@products = @catalog.products.all
respond_with(@business, @catalog)
end
但是我收到此错误:
CatalogsController GET 'show' should show products
Failure/Error: @catalog.should_receive(:products).and_return([@product1, @product2])
(#<Catalog:0x000001016185d0>).products(any args)
expected: 1 time
received: 0 times
# ./spec/controllers/catalogs_controller_spec.rb:36:in `block (3 levels) in <top (required)>'
此外,此代码块还将指示业务模型尚未收到 find 方法:
Business.should_receive(:find).with(@business.slug).and_return(@business)
这里的问题是您在规范中设置的@catalog实例变量与控制器中的@catalog实例变量不同。
规范中的@catalog将永远不会收到发送到控制器中@catalog的任何消息。
相反,您需要做的是在规范中更改此设置:
@catalog.should_receive(:products).and_return([@product1, @product2])
自
Catalog.any_instance.should_receive(:products).and_return([@product1, @product2])
在此处查看有关 any_instance.should_receive 的 RSpec 文档:https://www.relishapp.com/rspec/rspec-mocks/v/2-6/docs/message-expectations/expect-a-message-on-any-instance-of-a-class