首页 文章

rspec 3.3中的Nil @controller错误,rails 4.2.0

提问于
浏览
2

我在运行任何后期创建rspec与控制器规格中缺少控制器变量相关时出错 .

我已经研究了至少一天这个问题,大多数问题都与无关的宝石有关,或者没有解决问题 .

我看到很多这样的错误:

失败/错误:post:create,{user:@user_attributes},format :: json RuntimeError:@controller is nil:确保在测试的安装方法中设置它 . #./spec/controllers/api/v0/users_controller_spec.rb:27:in`block(3 levels)in'

供参考,这是我的Gemfile:

source 'https://rubygems.org'


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

gem 'activerecord-postgis-adapter'
gem 'rgeo'
gem 'rb-readline'
gem "devise"
gem "responders"

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'

  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'

  gem "rspec-rails", "~> 3.3"
end

group :test do

  #gem "shoulda-matchers"
  gem "factory_girl_rails"
  gem 'ffaker'
end

这是我的 spec/controllers/api/v0/users_controller_spec.rb

require 'spec_helper'

describe Api::V0::UsersController do
  before(:each) { request.headers['Accept'] = "application/market.v0" }

  describe "GET #show" do
    before(:each) do
      @user = FactoryGirl.create :user
      get :show, id: @user.id, format: :json
    end

    it "returns the information about a reporter on a hash" do
      user_response = JSON.parse(response.body, symbolize_names: true)
      expect(user_response[:email]).to eql @user.email
    end

    #it { should respond_with 200 }
    it { expect(response).to have_http_status(200) }
  end
end

  describe "POST #create" do

    context "when is successfully created" do
      before(:each) do
        @user_attributes = FactoryGirl.attributes_for :user
        post :create, { user: @user_attributes }, format: :json
      end

      it "renders the json representation for the user record just created" do
        user_response = JSON.parse(response.body, symbolize_names: true)
        expect(user_response[:email]).to eql @user_attributes[:email]
      end

      it { expect(response).to have_http_status(201) }
    end

    context "when is not created" do
      before(:each) do
        #notice I'm not including the email
        @invalid_user_attributes = { password: "12345678",
                                     password_confirmation: "12345678" }
        post :create, { user: @invalid_user_attributes }, format: :json
      end

      it "renders an errors json" do
        user_response = JSON.parse(response.body, symbolize_names: true)
        expect(user_response).to have_key(:errors)
      end

      it "renders the json errors on why the user could not be created" do
        user_response = JSON.parse(response.body, symbolize_names: true)
        expect(user_response[:errors][:email]).to include "can't be blank"
      end

      it { expect(response).to have_http_status(422) }
    end
  end

这是我的 spec_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  # ## Mock Framework
  #
  # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # If true, the base class of anonymous controllers will be inferred
  # automatically. This will be the default behavior in future versions of
  # rspec-rails.
  config.infer_base_class_for_anonymous_controllers = false

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"

  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  #
  # You can disable this behaviour by removing the line below, and instead
  # explictly tag your specs with their type, e.g.:
  #
  #     describe UsersController, :type => :controller do
  #       # ...
  #     end
  #
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/v/3-0/docs
  config.infer_spec_type_from_file_location!
end

这是 app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

最后我的 app/controllers/api/v0/users_controller.rb

require 'application_controller.rb'

class Api::V0::UsersController < ApplicationController
  respond_to :json

  def show
    #respond_to do |format|
    #  format.json { render request.format.to_sym => User.find(params[:id]) }
    #end
    respond_with User.find(params[:id])
  end

    def create
    user = User.new(user_params)
    if user.save
      render json: user, status: 201, location: [:api, user]
    else
      render json: { errors: user.errors }, status: 422
    end
  end

  private

  def user_params
    params.require(:user).permit(:email, :password, :password_confirmation)
  end
end

1 回答

  • 1

    在您的代码中,(参见您发布的规范中的第19行)您所拥有的位置:

    describe Api::V0::UsersController do
      before(:each) { request.headers['Accept'] = "application/market.v0" }
    
      describe "GET #show" do
        before(:each) do
          @user = FactoryGirl.create :user
          get :show, id: @user.id, format: :json
        end
    
        it "returns the information about a reporter on a hash" do
          user_response = JSON.parse(response.body, symbolize_names: true)
          expect(user_response[:email]).to eql @user.email
        end
    
        #it { should respond_with 200 }
        it { expect(response).to have_http_status(200) }
      end
    end
    

    你这里只需要1个结束 . 最后一个“it”语句不需要结束 . 它没有do块,所以不应该有它的结束 . 在最后两行(结尾)中,第一行结束您描述的“GET #show”块 . 因此,第二个额外的结束关闭第一个描述块:

    describe Api::V0::UsersController do
    

    你的描述Api :: V0 :: UserController块被关闭,因此你得到的无控制器错误发生在第27行 . 一旦你的Api :: V0 :: UserController块被关闭,当下一个描述块执行时,控制器是nil .

相关问题