[英]My Rails controller test is not inheriting the ApplicationController methods
我在公共区域有给定方法的ApplicationController
def current_user
session[:user]
end
和另一个控制器
ObjetosController < ApplicationController
需要访问这种方法,并且在运行测试时出现了一个可怕的错误(rake test:functionals):
NameError:未定义的本地变量或方法“ current_user”
我正在使用Ruby 2.0.0和Rails 4.0。 我已经在Google和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
解决了。
在我的ApplicationController类中,我实例化了为每个环境动态定义的一些类。 我还在使用每个环境定义的一些常量。
由于此应用尚未发布到登台或生产阶段,因此仅在config / environments / development.rb文件中定义了这些值。 我将它们添加到config / environments / test.rb,现在可以使用了!
我因这个问题浪费了数小时,我真的对Rails(或ruby?)感到失望,因为它根本没有显示任何错误...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.