测试数据(Fixtures)
│
▼
test/fixtures/users.yml
test/fixtures/articles.yml
│
▼
每条测试前自动加载到 test 数据库(每测一事务回滚)
跟着做
步骤 1:模型测试
# test/models/article_test.rb
require "test_helper"
class ArticleTest < ActiveSupport::TestCase
test "标题必填" do
article = Article.new(title: "", body: "正文")
assert_not article.valid?
assert_includes article.errors[:title], "can't be blank"
end
test "发布时必须有正文" do
article = articles(:published_no_body) # 引用 fixture
assert_not article.valid?
assert_includes article.errors[:body], "发布前必须填写正文"
end
test "标题唯一" do
existing = articles(:one)
duplicate = Article.new(title: existing.title, body: "正文")
assert_not duplicate.save
assert_includes duplicate.errors[:title], "has already been taken"
end
end
# test/controllers/articles_controller_test.rb
require "test_helper"
class ArticlesControllerTest < ActionDispatch::IntegrationTest
test "未登录不能新建文章" do
get new_article_url
assert_redirected_to login_url
end
test "创建文章并重定向" do
login_as users(:alice) # 自定义测试辅助方法
assert_difference "Article.count", 1 do
post articles_url, params: { article: { title: "新文章", body: "正文正文正文" } }
end
assert_redirected_to article_url(Article.last)
follow_redirect!
assert_select "h1", "新文章"
end
end
# test/test_helper.rb 里加辅助方法
class ActionDispatch::IntegrationTest
def login_as(user)
post login_url, params: { email: user.email, password: "secret123" }
end
end
assert_difference 检查数据库计数变化;follow_redirect! 跟随重定向继续断言;assert_select 用 CSS 选择器断言 HTML 内容。
步骤 4:系统测试(浏览器级)
# test/system/articles_test.rb
require "application_system_test_case"
class ArticlesTest < ApplicationSystemTestCase
test "新建文章完整流程" do
login_as users(:alice)
visit articles_url
click_on "写新文章"
fill_in "标题", with: "系统测试文章"
fill_in "正文", with: "这是系统测试的正文内容,要够长。"
click_on "保存"
assert_text "文章创建成功"
assert_text "系统测试文章"
end
end