Rspec错误NameError:Factory上未初始化的常量

Eri*_*win 5 rspec ruby-on-rails

我正在用两个工厂创建一组测试,见下文:

规格/工厂/ 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
Run Code Online (Sandbox Code Playgroud)

但是,在spec/controllers/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
Run Code Online (Sandbox Code Playgroud)

错误:

  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)>'
Run Code Online (Sandbox Code Playgroud)

此代码类似于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
Run Code Online (Sandbox Code Playgroud)

请注意:page_invalid工厂上的:class =>选项.