【问题标题】:Rspec error NameError: uninitialized constant on a FactoryRspec错误NameError:工厂上的未初始化常量
【发布时间】:2013-06-04 03:06:11
【问题描述】:

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

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

但是,在 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 工厂。

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    试试这个:

    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=> 选项。

    【讨论】:

    • 我在尝试测试可安装引擎时遇到了同样的问题。这派上用场了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2016-09-19
    相关资源
    最近更新 更多