2012-05-11 62 views
1

我正在构建一个简单的测试,以便为用户显示产品。我的规格如下所示:Rails 3.2使用FactoryGirl RSpec测试混淆

require 'spec_helper' 

describe "Show Products" do 
    it "Displays a user's products" do 
    product = Factory(:product) 
    visit products_path 
    page.should have_content("ABC1") 
    end 
end 

和我厂的产品是这样的:

FactoryGirl.define do 
    factory :product do 
    sequence(:identifier, 1000) {|n| "ABC#{n}" } 
    end 
end 

我有一个简单的观点:

<table id="products"> 
    <thead> 
<th>Product ID</th> 
    </thead> 
    <tbody> 
    <% for product in @products %> 
     <tr> 
     <td><%= @product.identifier %></td> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 

我得到的错误是,没有@products这样的东西。那么,是的。这是我的问题。由于我的工厂被定义为“产品”,并且它有一个序列,我如何将“产品”的值放入一个名为“产品”的变量中。

我基本上被FactoryGirl语法混淆了。如何在一条生产线上生成多个产品,但工厂名称必须与模型匹配?

回答

1

实例变量@products最有可能分配在您的ProductsController的索引操作中,或者如果没有,它可能应该在那里定义。

通常,在请求规范中发生的事情是,您使用Factory创建一个持久化在数据库中的对象,然后控制器检索这些记录并将它们分配给可供视图使用的实例变量。因为它看起来像你渲染指数,我希望看到这样的事情在你的控制器:

class ProductsController < ApplicationController::Base 
    def index 
    @products = Product.all 
    end 
end 

这个实例变量将提供给视图呈现时。

另外,它看起来像你在你的视图中有一个错字。在迭代器您有:

for product in @products 
    # do something with product 
end 

这是要遍历的每一件产品,使可变“产品”的块中可用。相反,你在块中使用@product,这似乎是一个错字。