config/database.yml 定義 development、test、production 三套數據庫配置,徹底隔離測試數據。
# 同步開發庫結構到測試庫 rake db:migrate rake db:test:prepare # 或 rake db:test:load
test/ ├── fixtures/ # 測試數據 ├── unit/ # Model 單元測試 ├── functional/ # Controller 功能測試 ├── integration/ # 多 Controller 集成測試 ├── performance/ # 性能測試 └── test_helper.rb # 全局配置、輔助方法
# test/fixtures/users.yml david: name: David Heinemeier Hansson birthday: 1979-10-15 profession: Systems development steve: name: Steve Ross Kellock birthday: 1974-09-27 profession: Guy with keyboard
<% earth_size = 20 %> mercury: size: <%= earth_size / 50 %> brightest_on: <%= 113.days.ago.to_s(:db) %> venus: size: <%= earth_size / 2 %> brightest_on: <%= 67.days.ago.to_s(:db) %>
# 自動加載到同名變量 user = users(:david) user.name # => "David Heinemeier Hansson"
# rails g model Post title:string content:text
# 生成 test/unit/post_test.rb
require 'test_helper'
class PostTest < ActiveSupport::TestCase
test "the truth" do
assert true
end
end
ActiveSupport::TestCase。test_ 開頭自動識別為測試用例。# 單文件 ruby -Itest test/unit/post_test.rb # 指定方法 ruby -Itest test/unit/post_test.rb -n test_the_truth # Rake 任務 rake test TEST=test/unit/user_test.rb
assert_redirected_to)。assigns(:post))。assert_select、assert_match)。
get :index
post :create, params: { post: { title: "Test" } }
put :update, params: { id: 1, post: { title: "Updated" } }
delete :destroy, params: { id: 1 }
head :show, params: { id: 1 }
assigns:實例變量(@post)。cookies:Cookie 值。flash:Flash 消息。session:Session 數據。@controller:當前 Controller 實例。@request:Request 對象。@response:Response 對象。
rails g integration_test user_flows
# test/integration/user_flows_test.rb
require 'test_helper'
class UserFlowsTest < ActionDispatch::IntegrationTest
fixtures :all
test "user registration and login flow" do
# 訪問註冊頁
get signup_path
assert_response :success
# 提交註冊
post users_path, params: { user: { name: "Test", email: "test@example.com", password: "secret" } }
assert_redirected_to root_path
follow_redirect!
assert_select "div.flash.notice", "Welcome!"
# 登出
delete logout_path
assert_redirected_to login_path
end
end
parallelize(workers: :number_of_processors) 加速大型測試套件。ActionDispatch::SystemTestCase 驅動真實瀏覽器(Chrome/Firefox Headless),測試 JavaScript 交互。SimpleCov 生成 HTML 報告,針對未覆蓋代碼補充用例。Rails 內建測試框架提供了從 Model 到 Controller 再到全鏈路的完整驗證能力。關鍵實踐:
測試不是成本,是對未來維護性的投資。