我的Rails控制器测试不继承ApplicationController方法

时间:2014-01-24 15:43:06

标签: ruby-on-rails ruby testing

我在公共区域有一个给定方法的ApplicationController

def current_user 
  session[:user]
end

和另一个控制器

ObjetosController < ApplicationController

需要访问这样的方法,我在运行测试时遇到了一个可怕的错误(rake test:functionals):

  

NameError:未定义的局部变量或方法`current_user'

     

我正在使用Ruby 2.0.0和Rails 4.0。我一直在谷歌和StackOverflow旅行几个小时,但没有发现任何相关信息。 也许有人可以给我一个提示或者帮我找一个答案吗?

如果它有帮助,如果我把垃圾放在ApplicationController中,并运行测试,它不会抱怨!!! 就像它正在加载这个类的另一个版本......

这是我的ObjetosController代码:

class ObjetosController < ApplicationController
  before_action :set_objeto, only: [:show, :edit, :update, :destroy]

  # GET /objetos
  # GET /objetos.json
  def index
    @objetos = Objeto.all
  end

  # GET /objetos/1
  # GET /objetos/1.json
  def show
  end

  # GET /objetos/new
  def new
    @objeto = Objeto.new
  end

  # GET /objetos/1/edit
  def edit
  end

  # POST /objetos
  # POST /objetos.json
  def create
    @objeto = Objeto.new(objeto_params)

    respond_to do |format|
      if @objeto.save
        format.html { redirect_to @objeto, notice: 'Objeto was successfully created.' }
        format.json { render action: 'show', status: :created, location: @objeto }
      else
        format.html { render action: 'new' }
        format.json { render json: @objeto.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /objetos/1
  # PATCH/PUT /objetos/1.json
  def update
    current_user
    respond_to do |format|
      if @objeto.update(objeto_params)
        format.html { redirect_to @objeto, notice: 'Objeto was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @objeto.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /objetos/1
  # DELETE /objetos/1.json
  def destroy
    @objeto.destroy
    respond_to do |format|
      format.html { redirect_to objetos_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_objeto
      @objeto = Objeto.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def objeto_params
      params.require(:objeto).permit(:nombre, :codigo_sgej)
    end
end

1 个答案:

答案 0 :(得分:0)

解决了它。

在我的ApplicationController类中,我实例化了为每个环境动态定义的一些类。我还使用了一些根据环境定义的常量。

由于此应用程序尚未发布到暂存或生产,我只在config / environments / development.rb文件中定义了这些值。我将它们添加到config / environments / test.rb中,现在它可以工作了!

我因为这个问题而浪费了几个小时,我真的对导轨(或红宝石?)感到失望,因为它没有显示任何错误...