2015-01-15 79 views
1

我嘗試重構我specs.I有觀點規格/視圖/ posts.html.haml_spec.rbNameError:未定義的局部變量或方法'後」爲#<FactoryGirl.Rspec

require 'rails_helper' 

describe 'posts/show' do 
    before(:each) do 
    @post = assign(:post, create(:post)) 
    @comments = assign(:comment, Kaminari.paginate_array([ 
     create(:comment, post: @post) 
    ]).page(1)) 
    end 

    it 'renders attributes in <p>' do 
    render 
    end 
end 

和我想要的代碼轉移到工廠規格/工廠/ posts.rb

FactoryGirl.define do 

    factory :post do 
    title Faker::Lorem.word 
    body Faker::Lorem.paragraph 


    trait :with_comments do 
     after(:create) do 
     create_list(:comment, post: post) 
     end 
    end 
    end 
end 

但是當我運行FactoryGirl.create(:post, :with_comments),殼告訴我一個錯誤

NameError: undefined local variable or method `post' for #<FactoryGirl::SyntaxRunner:0x00000003b44f08> 

怎麼修?

對不起我的英語不好

+0

'create_list(:comment,post:post)'。那裏的局部變量'post'是什麼?它應該是':post'嗎? – ptd 2015-01-15 15:34:23

+0

'create_list(:comment,post:create(:post))'它應該是這樣的東西,讓你有'後工廠' – 2015-01-15 15:38:54

回答

1

您沒有通過對象after_create塊。你也沒有;指定要創建的評論數量。改變你的性狀爲:

trait :with_comments do 
    after(:create) do |post| 
    create_list(:comment, <number_of_comments>, post: post) 
    end 
end 
+1

謝謝你的答案,但shell渲染另一個錯誤。 NoMethodError:未定義的方法'時間'爲#<哈希值:0x000000083c1da8> – vveare138 2015-01-15 15:48:31

+1

這是因爲您沒有指定要創建的註釋的數量。 – BroiSatse 2015-01-15 15:52:17

+0

在我的回答中有解釋嗎? – BroiSatse 2015-01-15 16:02:58