Rails集成测试 #
一、控制器测试 #
1.1 测试文件 #
ruby
# test/controllers/articles_controller_test.rb
require 'test_helper'
class ArticlesControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get articles_url
assert_response :success
end
test "should create article" do
post articles_url, params: { article: { title: 'Test', body: 'Body' } }
assert_response :redirect
end
end
二、请求测试 #
2.1 API测试 #
ruby
# test/integration/api_test.rb
require 'test_helper'
class ApiTest < ActionDispatch::IntegrationTest
test "should get articles" do
get api_v1_articles_url, as: :json
assert_response :success
json = JSON.parse(response.body)
assert_kind_of Array, json
end
end
三、总结 #
3.1 核心要点 #
| 要点 | 说明 |
|---|---|
| get/post | HTTP方法 |
| assert_response | 响应断言 |
| as: :json | JSON格式 |
3.2 下一步 #
现在你已经掌握了集成测试,接下来让我们学习 系统测试,深入了解Rails的端到端测试!
最后更新:2026-03-28