登录 主页

rails controller unit test 例子

2023-10-10 11:40AM

 这是一个 car_controller 的单元测试

# test/controllers/cars_controller_test.rb

require 'test_helper'
class CarsControllerTest < ActionDispatch::IntegrationTest
   include Devise::Test::IntegrationHelpers

   setup do
     @manager = managers(:manager1)
     sign_in @manager
     @car = cars(:one)
   end

   test "should get index" do
     get cars_url
     assert_response :success                                                                         
   end
    
   test "should get new" do                                                                           
     get new_car_url
     assert_response :success
   end
    
    test "should create car" do

      # 因为已经增加了 test/fixtures/enterprises.yml 和 test/fixtures/material_reserves.yml 文件,所以这里可以直接使用 enterprises(:one).id 和 material_reserves(:one).id
      post cars_url, params: { car: { enterprise_id: enterprises(:one).id, material_reserf_id: material_reserves(:one).id,  car_number: "新A325720" , weight: "68吨0", driver_name: "李明0", driver_tel: 18388668    8450,
                                          driver_id_card_number: 411020155466374560, driver_address: "乌鲁木齐市天山区中山路6号0"} }
      assert_redirected_to "/goods/notice"
    end 
   
    test "should show car" do
      get car_url(@car)
      assert_response :success
    end
   
    test "should get edit" do
      get edit_car_url(@car)
      assert_response :success
    end
   
    test "should update car" do
       patch car_url(@car), params: { car: { enterprise_id: 2, car_number: "新A22572"  , weight: "66吨", driver_name: "李显", driver_tel: 18388668845,
                                          driver_id_card_number: 41102015546637455, driver_address: "乌鲁木齐市天山区中山路6号"} }
       assert_equal "新A22572", assigns(:car).car_number
  end

   test "should destroy car" do
      assert_difference("Car.count", -1) do
         delete car_url(@car)
      end
     assert_redirected_to cars_url
   end
 end

运行这个单元测试:

$ bundle exec rails test test/controllers/cars_controller_test.rb

Run options: --seed 23866

# Running:

......
.

Finished in 0.527401s, 13.2726 runs/s, 17.0648 assertions/s.
7 runs, 9 assertions, 0 failures, 0 errors, 0 skips

 

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论