Rails - 编写测试

参考书籍: Ruby on Rails教程(第四版)

一个简单测试

编写测试文件

找到test目录下对应的测试文件 例如:test/controllers/static_pages_controller_test.rb

# 以下为之前使用"rails generator controller StaticPages home help"
# 命令时自动生成的测试代码
require 'test_helper'

class StaticPagesControllerTest < ActionDispatch::IntegrationTest
  test 'should get home' do
    get static_pages_home_url
    assert_response :success
  end

  test 'should get help' do
    get static_pages_help_url
    assert_response :success
  end
end

启动测试

rails test

测试组件通过会以绿色显示,不通过的会以红色显示(颜色区分效果需要添加MiniTest依赖)

测试遇红及解决

在测试文件static_pages_controller_test.rb中添加如下代码

  test "should get about" do
    get static_pages_about_url
    assert_response :success
  end

再次启动测试,会发现有一个错误发生❌ 错误原因如下:NameError: undefined local variable or method 'static_pages_about_url'

  • 上面的错误消息提示我们没有定义获取about页面的Rails代码,实际上是提示我们需要在路由文件中添加相应路由规则
  • 找到config/routes.rb文件,添加"get 'static_pages/about'到文件当中
  • 新增的代码告诉Rails,将发给static_pages/about页面的GET请求交给StaticPages控制器的about方法进行处理,同时会自动创建一个辅助方法static_pages_about_url

再次启动测试,还是有错误发生❌ 错误原因如下:AbstractController::ActionNotFound: The action 'about' could not be found for StaticPagesController

  • 上面的错误消息提示我们StaticPages控制器缺少about方法
  • 找到StaticPages控制器并向其添加about方法

再次启动测试,仍然有错误发生❌ 错误原因如下:ActionController::UnknownFormat: StaticPagesController#about is missing a template for this request format and variant

  • 上面的错误消息表明about方法缺少对应的模版文件,在Rails中模版就是视图
  • 在app/views/static_pages目录中,新建一个文件取名about.html.erb,加入自己需要的内容即可

再次启动测试,会发现测试可以通过✅

高级测试技术初步了解

MiniTest报告

为了Rails应用的测试适时显示红色和绿色,需要在测试辅助文件中引入MiniTest

# test/test_helper.rb文件代码如下
ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"
require 'minitest/reporters'
Minitest::Reporters.use!

class ActiveSupport::TestCase
  # Run tests in parallel with specified workers
  parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

使用Guard进行自动测试

频繁使用rails test命令进行手动测试,显得有点笨拙 为了避免这种不便,我们可以使用引入Guard自动进行测试 Guard会监视文件系统的变动,并自动执行相应的测试 例如:修改了static_pages_controller_test.rb文件,那么Guard只会运行这个文件中的测试 我们还可以配置Guard,让它在模版文件被修改后,也会自动运行对应的测试文件中的测试

引入guard依赖

# test环境下的特有依赖
group :test do
  # gem "capybara"
  # gem "selenium-webdriver"
  # gem "webdrivers"
  gem 'rails-controller-testing', '1.0.5'
  gem 'minitest', '5.10.3'
  gem 'minitest-reporters', '1.1.9'
  gem 'guard', '2.18.0'
  gem 'guard-minitest', '2.4.4'
  gem 'rb-readline'
end

初始化Guardfile文件

bundle exec guard init

修改Guardfile文件

# 下面这行代码会让Guard使用Rails提供的Spring服务器,减少加载时间,而且启动时不运行整个测试组件
guard :minitest, spring: "bin/rails test", all_on_start: false do
  watch(%r{^test/(.*)/?(.*)_test\.rb$})
  watch('test/test_helper.rb') { 'test' }
  watch('config/routes.rb')    { integration_tests }
  watch(%r{^app/models/(.*?)\.rb$}) do |matches|
    "test/models/#{matches[1]}_test.rb"
  end
  watch(%r{^app/controllers/(.*?)_controller\.rb$}) do |matches|
    resource_tests(matches[1])
  end
  watch(%r{^app/views/([^/]*?)/.*\.html\.erb$}) do |matches|
    ["test/controllers/#{matches[1]}_controller_test.rb"] +
      integration_tests(matches[1])
  end
  watch(%r{^app/helpers/(.*?)_helper\.rb$}) do |matches|
    integration_tests(matches[1])
  end
  watch('app/views/layouts/application.html.erb') do
    'test/integration/site_layout_test.rb'
  end
  watch('app/helpers/sessions_helper.rb') do
    integration_tests << 'test/helpers/sessions_helper_test.rb'
  end
  watch('app/controllers/sessions_controller.rb') do
    ['test/controllers/sessions_controller_test.rb',
     'test/integration/users_login_test.rb']
  end
  watch('app/controllers/account_activations_controller.rb') do
    'test/integration/users_signup_test.rb'
  end
  watch(%r{app/views/users/*}) do
    resource_tests('users') +
      ['test/integration/microposts_interface_test.rb']
  end
end

# Returns the integration tests corresponding to the given resource.
def integration_tests(resource = :all)
  if resource == :all
    Dir["test/integration/*"]
  else
    Dir["test/integration/#{resource}_*.rb"]
  end
end

# Returns the controller tests corresponding to the given resource.
def controller_test(resource)
  "test/controllers/#{resource}_controller_test.rb"
end

# Returns all tests for the given resource.
def resource_tests(resource)
  integration_tests(resource) << controller_test(resource)
end

启动Guard

bundle exec guard

尝试修改一下控制器、模版视图、测试等文件,可以发现在修改保存后,guard会自动执行测试