0

注意:一个企业有很多目录,有产品,一个目录有很多产品。关联已正确定义,并且它们在应用程序前端工作。但是我不能通过这个测试。我正在使用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)
4

1 回答 1

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一流的

于 2012-06-21T06:49:55.733 回答