5

2 つのファクトリを使用して一連のテストを作成しています。以下を参照してください。

仕様/工場/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

ただし、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

エラー:

  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 ファクトリが認識されない理由がわかりません。

4

1 に答える 1

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 ファクトリの :class => オプションに注意してください。

于 2013-06-04T03:14:46.660 に答える