注意:企业有许多目录并且有产品,而目录有很多产品。这些关联已正确定义,并且它们正在应用程序前端中运行。但我不能让这个测试通过。我正在使用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
使用此show动作:
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)
答案 0 :(得分:1)
这里的问题是您在规范中设置的@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