2013-04-15 90 views
0

我有使用FactoryGirl的這個問題。使用工廠測試時未定義的方法`to_i'用於<Array:0x ########>

我每次運行測試,它出現與錯誤:數組

我不能看到它正試圖轉換爲整數未定義的方法`to_i」。我最好的猜測是它試圖將客戶記錄保存爲一個數字,而不是隻保存記錄的ID。我試圖搜索文檔,看看我是否錯誤地設置了我的工廠。

我已經運行耙db:test:prepare希望它是。

你能看出發生了什麼問題嗎?

規格/ factories.rb

FactoryGirl.define do 

    factory :client do 
    name  "Example" 
    email "[email protected]" 
    end 

    factory :book do 
    title "Book Title" 
    client_id {[FactoryGirl.create(:client)]} 
    end 

end 

規格/視圖/書籍/ index.html.erb_spec.rb

require 'spec_helper' 

describe "books/index" do 
    before do 
    FactoryGirl.create(:book) 
    end 

    it "renders a list of books" do 
    render 
    # Run the generator again with the --webrat flag if you want to use webrat matchers 
    assert_select "tr>td", :text => "Title".to_s, :count => 2 
    assert_select "tr>td", :text => 1.to_s, :count => 2 
    end 
end 

測試輸出

1) books/index renders a list of books 
    Failure/Error: FactoryGirl.create(:book) 
    NoMethodError: 
     undefined method `to_i' for #<Array:0x########> 
    # ./spec/views/books/index.html.erb_spec.rb:5:in `(root)' 

回答

1

您在定義工廠時犯了一個錯誤。

不要在定義中調用FactoryGirl.create...

假設書有很多客戶(雖然這很奇怪),但您可以在客戶端提到書。像這樣

FactoryGirl.define do 

    factory :client do 
    name  "Example" 
    email "[email protected]" 
    book # Revised here. book refers to the symbol :book 
    end 

    factory :book do 
    title "Book Title" 
    end 

end 

就這樣。你測試應該能夠過去。

P.S旁註約模型關聯:

在你的設置中,一個客戶端只能有一本書!企業主不能通過這樣的銷售很快致富。一個正確的邏輯應該是:

客戶可以具有很多訂單,

一個訂單可以有很多項目

的項目只有一本書(ID),但可能有很多個。

但這是另一回事。

+0

謝謝!是的,我意識到現在,我掀起了一個簡化的例子來說明發生了什麼問題。也許這是某個地方人們在同一時間共享書籍:P ...我將編輯我的查詢。 – Crimbo

相關問題