【问题标题】:rspec Ruby on Rails uninitialized constant RecipesController::Recipesrspec Ruby on Rails 未初始化常量RecipesController::Recipes
【发布时间】:2015-10-18 17:26:15
【问题描述】:

您好,我正在使用 Rspec 对我的应用程序进行一些测试(这是我第一次使用它)

这是我的测试文件,位于 spec/controllers/recipes_controller_spec.rb

require 'spec_helper'

describe RecipesController do
  render_views
  describe "index" do
    before do
      Recipe.create!(name: 'Baked Potato w/ Cheese')
      Recipe.create!(name: 'Garlic Mashed Potatoes')
      Recipe.create!(name: 'Potatoes Au Gratin')
      Recipe.create!(name: 'Baked Brussel Sprouts')

      xhr :get, :index, format: :json, keywords: keywords
    end

    subject(:results) { JSON.parse(response.body) }

    def extract_name
      ->(object) { object["name"] }
    end

    context "when the search finds results" do
      let(:keywords) { 'baked' }
      it 'should 200' do
        expect(response.status).to eq(200)
      end
      it 'should return two results' do
        expect(results.size).to eq(2)
      end
      it "should include 'Baked Potato w/ Cheese'" do
        expect(results.map(&extract_name)).to include('Baked Potato w/ Cheese')
      end
      it "should include 'Baked Brussel Sprouts'" do
        expect(results.map(&extract_name)).to include('Baked Brussel Sprouts')
      end
    end

    context "when the search doesn't find results" do
      let(:keywords) { 'foo' }
      it 'should return no results' do
        expect(results.size).to eq(0)
      end
    end

  end
end

当我尝试通过命令执行它时:

bundle exec rspec spec/controllers/recipes_controller_spec.rb

我的所有测试都因这个错误而失败:

Failure/Error: xhr :get, :index, format: :json, keywords: keywords
     NameError:
       uninitialized constant RecipesController::Recipes
     # ./app/controllers/recipes_controller.rb:4:in `index'
     # ./spec/controllers/recipes_controller_spec.rb:12:in `block (3 levels) in <top (required)>'

我试图查看我所有的代码,但我没有发现错误

【问题讨论】:

  • 它位于你的控制器中,第 4 行。你能把这个文件也过去吗?
  • 看起来你在recipes_controllerindex 方法中有Recipes 而不是Recipe

标签: ruby-on-rails ruby rspec


【解决方案1】:
NameError: uninitialized constant RecipesController::Recipes

意味着您在控制器中的某处(index 中的第 4 行)使用了 Recipes 而不是 Recipe,并且由于您的模型称为 Recipe(单数),因此您将收到 NameError 异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多