ruby-on-rails - 更新、显示和销毁的 Controller 测试不适用于引用的类

标签 ruby-on-rails ruby unit-testing testing

我有“用户”和“empresas”,我使用脚手架命令为“empresas”生成初始 CRUD,然后我将用户 ID 放入 empresas 和所有模型需要的,所以我想要的只是作为 empresa 所有者的用户可以访问“显示”、“更新”和“销毁”,我有一个 correct_user 函数,在将其应用于操作之前,一切正常,除非测试,我只是将登录应用到原始脚手架测试中。

Empresas Controller

class EmpresasController < ApplicationController
  before_action :set_empresa, only: [:show, :edit, :update, :destroy]
  before_action :logged_in_user, only: [:update, :show, :index, :create, :destroy]
  before_action :correct_user,   only: [:show, :update, :destroy]

  # GET /empresas
  # GET /empresas.json
  def index
    @empresas = current_user.empresas.all
  end

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

  # GET /empresas/new
  def new
    @empresa = Empresa.new
  end

  # GET /empresas/1/edit
  def edit
  end

  # POST /empresas
  # POST /empresas.json
  def create
    @empresa = current_user.empresas.build(empresa_params)
    respond_to do |format|
      if @empresa.save
        format.html { redirect_to @empresa, notice: 'Empresa criada com sucesso.' }
        format.json { render :show, status: :created, location: @empresa }
      else
        format.html { render :new }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /empresas/1
  # PATCH/PUT /empresas/1.json
  def update
    respond_to do |format|
      if @empresa.update(empresa_params)
        format.html { redirect_to @empresa, notice: 'Empresa alterada com sucesso.' }
        format.json { render :show, status: :ok, location: @empresa }
      else
        format.html { render :edit }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /empresas/1
  # DELETE /empresas/1.json
  def destroy
    @empresa.destroy
    respond_to do |format|
      format.html { redirect_to empresas_url, notice: 'Empresa removida com sucesso.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_empresa
      @empresa = current_user.empresas.find_by(id: params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def empresa_params
      params.require(:empresa).permit(:nome_fantasia, :email, :razao_soc, :cnpj)
    end

    def correct_user
      @empresa = current_user.empresas.find_by(id: params[:id])
      redirect_to empresas_url if @empresa.nil?
    end

end

Empresas_controller test

require 'test_helper'

class EmpresasControllerTest < ActionController::TestCase
  setup do
    @user = users(:carlos)
    @empresa = empresas(:one)
    @empresa.user_id = @user.id
  end

  test "should get index" do
    log_in_as(users(:carlos))
    get :index
    assert_response :success
    assert_not_nil assigns(:empresas)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create empresa" do
    log_in_as(users(:carlos))
    assert_difference('Empresa.count') do
      post :create, empresa: {email: @empresa.email, nome_fantasia: @empresa.nome_fantasia, cnpj: @empresa.cnpj, razao_soc: @empresa.razao_soc }
    end

    assert_redirected_to empresa_path(assigns(:empresa))
  end

  test "should show empresa" do
    log_in_as(users(:carlos))
    get :show, id: @empresa
    assert_response :success
  end

  test "should get edit" do
    log_in_as(users(:carlos))
    get :edit, id: @empresa
    assert_response :success
  end

  test "should update empresa" do
    log_in_as(users(:carlos))
    patch :update, id: @empresa, empresa: {email: @empresa.email, nome_fantasia: @empresa.nome_fantasia, cnpj: @empresa.cnpj, razao_soc: @empresa.razao_soc }
    assert_redirected_to empresa_path(assigns(:empresa))
  end

  test "should destroy empresa" do
    log_in_as(users(:carlos))
    assert_difference('Empresa.count', -1) do
      delete :destroy, id: @empresa
    end

    assert_redirected_to empresas_path
  end


end

The erros msgs

FAIL["test_should_destroy_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_destroy_empresa#EmpresasControllerTest (1447412845.23s)
        "Empresa.count" didn't change by -1.
        Expected: 2
          Actual: 3
        test/controllers/empresas_controller_test.rb:51:in `block in <class:EmpresasControllerTest>'

ERROR["test_should_get_edit", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_get_edit#EmpresasControllerTest (1447412845.33s)
ActionView::Template::Error:         ActionView::Template::Error: First argument in form cannot contain nil or be empty
            app/views/empresas/_form.html.erb:1:in `_app_views_empresas__form_html_erb___3156194878750235915_67173720'
            app/views/empresas/edit.html.erb:4:in `_app_views_empresas_edit_html_erb___622806155688133729_66667680'
            test/controllers/empresas_controller_test.rb:39:in `block in <class:EmpresasControllerTest>'
        app/views/empresas/_form.html.erb:1:in `_app_views_empresas__form_html_erb___3156194878750235915_67173720'
        app/views/empresas/edit.html.erb:4:in `_app_views_empresas_edit_html_erb___622806155688133729_66667680'
        test/controllers/empresas_controller_test.rb:39:in `block in <class:EmpresasControllerTest>'

 FAIL["test_should_show_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_show_empresa#EmpresasControllerTest (1447412845.35s)
        Expected response to be a <success>, but was <302>
        test/controllers/empresas_controller_test.rb:34:in `block in <class:EmpresasControllerTest>'

ERROR["test_should_update_empresa", EmpresasControllerTest, 2015-11-13 11:07:25 +0000]
 test_should_update_empresa#EmpresasControllerTest (1447412845.36s)
ActionController::UrlGenerationError:         ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"empresas", :id=>nil} missing required keys: [:id]
            test/controllers/empresas_controller_test.rb:46:in `block in <class:EmpresasControllerTest>'
        test/controllers/empresas_controller_test.rb:46:in `block in <class:EmpresasControllerTest>'

  61/61: [==================================================================================================================] 100% Time: 00:00:02, Time: 00:00:02

Finished in 2.21698s
61 tests, 166 assertions, 2 failures, 2 errors, 0 skips

一切正常,但我真的很想学习测试

最佳答案

那是因为用户不是正确的用户。你需要添加

@empresa.save

之后

@empresa.user_id = @user.id

在您的测试 Controller 中确保用户-empresa 关系建立在数据库中。

关于ruby-on-rails - 更新、显示和销毁的 Controller 测试不适用于引用的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34009767/

相关文章:

ruby-on-rails - Rails has_many 但在关联模型的列上是唯一的

Ruby:创建 Gzipped Tar 存档

java - 使用mockito调用方法时如何检查方法参数?

ruby-on-rails - 当我运行 rspec 时,我收到一条错误消息,声称 bcrypt-ruby 不是包的一部分

sql - 如何在 Rails 控制台中的某些值之间添加值

javascript - 无法在生产环境中实例化模块

ruby-on-rails - 如何删除 "---\n- ' '\n- "在 ruby​​ on rails 数据库中保存的新行空间

Ruby 通过代理打开 uri 下载

scala - 如何在 Akka Cluster 中测试订阅者的接收方法?

python - Django TestCase 测试顺序