【问题标题】:Rails Factory Girl RSpec Testing Has-Many Relationship of Nested ResourcesRails Factory Girl RSpec 测试有很多嵌套资源的关系
【发布时间】:2012-06-21 02:20:09
【问题描述】:

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

此外,这个代码块还会表明Business model没有收到find方法:

Business.should_receive(:find).with(@business.slug).and_return(@business)

【问题讨论】:

  • Business.should_receive 出现什么错误,预期 1 次,收到 0 次?

标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot friendly-id


【解决方案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

【讨论】:

  • 太棒了。请注意,这条线:@products = @catalog.products.all 给了我一个 undefined method 'all' for &lt;Array...&gt; 。删除 '.all' 使测试通过
  • 不错,很高兴你把它整理好了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多