Ruby on Rails控制器测试失败

时间:2018-03-18 11:27:00

标签: ruby-on-rails ruby testing count controller

除了其他一些失败,我主要在这里得到这个:

FAIL["test_should_create_kiga", Minitest::Result, 1.6827512969975942]
test_should_create_kiga#Minitest::Result (1.68s)
    "Kiga.count" didn't change by 1.
    Expected: 4
      Actual: 3
    test/controllers/kigas_controller_test.rb:20:in `block in <class:KigasControllerTest>'

我是Ruby的新手,我不知道为什么它会期待四个kigas而不是三个?在kigas的yml文件中,我只有三个kigas样本:

one:
name: MyString
city: MyString
postalcode: 1
streed: MyString
add_number: 1
capacity: 1
accessible: false
halalkit: false
koschakit: false
vegekit: false
vegankit: false
allday: false
user_id: 8
image_file_name: MyString
image_content_type: MyString
description: MyString

two:
name: MyString
city: MyString
postalcode: 1
streed: MyString
add_number: 1
capacity: 1
accessible: false
halalkit: false
koschakit: false
vegekit: false
vegankit: false
allday: false
user_id: 2
image_file_name: "kiga3.jpeg"
image_content_type: "image/jpeg"
description: MyString



three:
name: MyString
city: MyString
postalcode: 1
streed: MyString
add_number: 1
capacity: 1
accessible: false
halalkit: false
koschakit: false
vegekit: false
vegankit: false
allday: false
user_id: 2
image_file_name: "kiga3.jpeg"
image_content_type: "image/jpeg"
description: MyString

应用程序/测试/控制器/ kigas_controller_test.rb

require 'test_helper'

class KigasControllerTest < ActionDispatch::IntegrationTest
 setup do
  @kiga = kigas(:one)
  @other_kiga = kigas(:two)
 end
[...]
 test "should create kiga" do
  assert_difference('Kiga.count') do
   post kigas_url, params: { kiga: { accessible: @kiga.accessible, add_number: @kiga.add_number, allday: @kiga.allday, capacity: @kiga.capacity, city: @kiga.city, halalkit: @kiga.halalkit, koschakit: @kiga.koschakit, name: @kiga.name, postalcode: @kiga.postalcode, streed: @kiga.streed, vegankit: @kiga.vegankit, vegekit: @kiga.vegekit, user_id: @kiga.user_id } }
 end

  assert_redirected_to kiga_url(Kiga.last)
 end
[...]
end

应用程序/控制器/ kigas_controller.rb

class KigasController < ApplicationController
before_action :set_kiga, only: [:show, :edit, :update, :destroy]
before_action :logged_in_user
 def create
   @kiga = Kiga.new kiga_params
   @kiga.user = current_user
   @kiga.save
   respond_to do |format|
     if @kiga.save
       format.html { redirect_to @kiga, notice: 'Kiga was successfully created.' }
       format.json { render :show, status: :created, location: @kiga }
     else
       format.html { render :new }
       format.json { render json: @kiga.errors, status: :unprocessable_entity }
     end
   end
 end
end

所以我的问题是,我不知道为什么测试期望在创建测试中有四个kigas,因为我在.yml文件中有三个样本。我对我的应用程序中的其他一些对象有同样的问题,所以这可能是我面临的一个根本问题? 我很高兴有任何帮助!

1 个答案:

答案 0 :(得分:1)

它期望四个kigas,因为它是assert_difference方法的工作方式。它预计您拥有的记录数量为+1。检查此答案:https://stackoverflow.com/a/3348262/7956790
现在的情况是,你的post kigas_url没有创建一个新的kiga,也许你的Kiga模型中有一个未通过的验证?