2012-05-11 99 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,這似乎是一個錯字。