Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec error NameError: uninitialized constant on a Factory

I am creating a set of tests with two factories, see below:

spec/factories/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

However, in spec/controllers/page_controller_spec.rb, the following test throws an error:

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

The error:

  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)>'

This code is analogous to code in Everyday Rails Rspec so I'm not sure why the page_invalid factory isn't being recognized.

like image 1000
Eric Baldwin Avatar asked Jun 04 '13 03:06

Eric Baldwin


1 Answers

Try this:

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

Notice the :class => option on your :page_invalid factory.

like image 66
Matt Allen Avatar answered Oct 21 '22 12:10

Matt Allen