2013-06-04 45 views
5

我創建一組測試有兩個工廠未初始化的常數,見下圖:Rspec的錯誤NameError:在工廠

規格/工廠/ page.rb

FactoryGirl.define do 
    factory :page do 
     title "Example Title" 
     content "Here is some sample content" 
     published_on "2013-06-02 02:28:12" 
    end 
    factory :page_invalid do 
     title "" 
     content "" 
     published_on "2013-06-02 02:28:12" 
    end 
end 

然而,投機/控制器/page_controller_spec.rb,下面的試驗引發錯誤:

describe "with invalid params" do 
    it "does not save the new page in the database" do 
    expect { 
     post :create, {page: attributes_for(:page_invalid)}, valid_session 
     }.to_not change(Page, :count).by(1) 
    end 

錯誤:

1) Api::PagesController POST create with invalid params does not save the new page in the database 
    Failure/Error: post :create, {page: attributes_for(:page_invalid)}, valid_session 
    NameError: 
     uninitialized constant PageInvalid 
    # ./spec/controllers/pages_controller_spec.rb:78:in `block (5 levels) in <top (required)>' 
    # ./spec/controllers/pages_controller_spec.rb:77:in `block (4 levels) in <top (required)>' 

此代碼類似於Everyday Rails Rspec中的代碼,所以我不確定爲什麼page_invalid工廠未被識別。

回答

10

試試這個:

FactoryGirl.define do 
    factory :page do 
    title "Example Title" 
    content "Here is some sample content" 
    published_on "2013-06-02 02:28:12" 
    end 
    factory :page_invalid, :class => "Page" do 
    title "" 
    content "" 
    published_on "2013-06-02 02:28:12" 
    end 
end 

注意的:page_invalid工廠:類=>你的選項。

+0

工作,謝謝 –

+0

我試圖測試可安裝引擎時有同樣的問題。這很方便。 –