未定义的局部变量或方法`question_params'尽管它被定义了

时间:2014-08-28 02:45:49

标签: ruby-on-rails ruby rspec

我正在使用CRUD练习TDD并遇到此错误:

undefined local variable or method `question_params' for #<QuestionsController:0x0000010618a248>

以下是我的规格(虽然我认为它们无关紧要):

 describe '#create'  do
   it 'assigns @question to a new question' do
     post :create
     expect(assigns(:question)).to be_a_new(Question)
   end

   it 'redirects to the question once created' do
     post :create
     expect(response).to redirect_to question_path(@question)
   end
 end

这是控制器:

class QuestionsController < ApplicationController
  def new
    @question = Question.new 
  end

  def show
    @question = Question.find(params[:id])
  end

  def create
    @question = Question.new(question_params) 

    if @question.save
      redirect_to @question
    else
      render :new
    end

    private

    def question_params
      params.require(:question).permit(:title, :body)
    end
  end
end

这笔交易是什么?

2 个答案:

答案 0 :(得分:2)

您在另一种方法question_params中定义了create。它应该是这样的:

class QuestionsController < ApplicationController
  def new
    @question = Question.new 
  end

  def show
    @question = Question.find(params[:id])
  end

  def create
    @question = Question.new(question_params) 

    if @question.save
      redirect_to @question
    else
      render :new
    end
  end

private

  def question_params
    params.require(:question).permit(:title, :body)
  end
end

答案 1 :(得分:1)

你的目的不排队。 create方法目前包含question_params方法。

试试这个:

def create
  @question = Question.new(question_params) 

  if @question.save
    redirect_to @question
  else
    render :new
  end
end

private

def question_params
  params.require(:question).permit(:title, :body)
end