Rails 4测试控制器故障

时间:2014-07-30 20:15:56

标签: ruby-on-rails unit-testing testing ruby-on-rails-4 actioncontroller

下午好,

我已经完成了一个类的脚手架,这里的例子是:用户 - 在我执行测试的那一刻,我看到了这个错误:

Minitest::Assertion: "User.count" didn't change by 1.
Expected: 3
  Actual: 2
test/controllers/users_controller_test.rb:20:in `block in <class:UsersControllerTest>'

错误的引用代码就是这个:

test "should create user" do
  assert_difference('User.count') do
    post :create, user: { name: 'test', password: 'secret', password_confirmation: 'secret' }
  end

  assert_redirected_to user_path(assigns(:user))
end

所以上面的代码是由脚手架创建的,我只是更改名称引用。

UserController中:

class UsersController < ApplicationController

  before_action :set_user, only: [:show, :edit, :update, :destroy, :reset_password]

  # GET /users
  # GET /users.json
  def index
    @users = super
  end

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

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)
    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: get_action_message }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    @user.update(user_params)
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: get_action_message }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: get_action_message }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :password, :password_confirmation)
    end

    def search_params
      super - ['password_digest']
    end

    def show_attributes
      @show_attributes = super - ['password_digest']
    end

end

的usermodel

class User < ActiveRecord::Base

  nilify_blanks

  validates :name, presence: true, uniqueness: true;

  has_secure_password

end

对于我能够理解的内容,“创建”它没有被执行。我把断点放在Controller上,但它并没有停在那里..

除了我糟糕的英语技能外,我做错了什么?

请求帮助!!

1 个答案:

答案 0 :(得分:-1)

小伙子们,

我发现了这个错误。

我忘记了用户会话