SuperAPI AI Directory

flutter-golden-test

Testing & quality

View repository

Updated 10-16 08:52

About this skill

Flutter Golden Test skill

Overview

An interactive skill that lets even Flutter beginners set up a Golden Test (Visual Regression Test) environment and create and run Golden Tests for components and screens.

Trigger conditions:

  • "I want to introduce Golden Tests", "Set up golden tests"
  • "I want to create screenshot tests", "Add UI tests"
  • "Write a Golden Test for a component"
  • "Run Golden Tests", "Update golden files"

Role: Expert Interviewer

As an experienced Flutter test engineer, you will conduct a requirements interview. The goals are:

  • Ask clear and concise questions one at a time
  • Understand the user's project environment
  • Build an appropriate Golden Test environment
  • Generate test code

Important: Do not ask multiple questions at once. Wait for the user's answer before proceeding to the next.

Operating modes

Mode determination flow

  1. First analyze the project and check whether a Golden Test environment exists
  2. If no environment exists, "Initial Setup Mode"
  3. If an environment exists, "Test Generation Mode" or "Test Execution/Update Mode"

Mode 1: Initial setup

Executed when no Golden Test environment exists.

Important: Execute all the following steps in order (skipping is prohibited)

Step Content Required
0 Explanation of Golden Tests ○
1 Project analysis ○
2 Font configuration check ○
3 Check whether Riverpod is used ○
4 Theme configuration check ○
5 Screen size check ○
6 Check whether image assets are used ○
7 Check test creation granularity ○
8 File generation ○

Step 0: Explanation of Golden Tests [0/8]

First, communicate the following:

「Golden Test(ゴールデンテスト)の環境をセットアップしますね。【Step 0/8】

■ Golden Testとは?
ウィジェットのスクリーンショットを保存し、以降の変更で見た目が意図せず変わっていないかを自動検証するテストです。UIの品質を保ちながら安心してリファクタリングできるようになります。

■ このスキルでできること
対話形式で環境構築からテスト作成までサポートします。テスト画像がうまく生成されない場合も、会話しながら一緒に解決していきますので、お気軽にご質問ください。

■ 具体例:こんなテストが作れます
例えば、以下のようなボタンウィジェットがあるとします:」

Then, present the following concrete examples:

「▼ 対象ウィジェット(例)
```dart
class PrimaryButton extends StatelessWidget {
  final String text;
  final VoidCallback? onPressed;

  const PrimaryButton({required this.text, this.onPressed});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(onPressed: onPressed, child: Text(text));
  }
}
```

▼ 生成されるテストコード
```dart
testWidgets('有効状態', (tester) async {
  await tester.pumpGoldenWidget(
    PrimaryButton(onPressed: () {}, text: '保存する'),
  );
  await expectLater(
    find.byType(PrimaryButton),
    matchesGoldenFile(
      GoldenFilePath.component('primary_button', 'enabled'),
    ),
  );
});
```

▼ 生成されるファイル
test/ui/components/
├── primary_button_golden_test.dart   ← テストコード
└── goldens/components/primary_button/
    ├── enabled.png                   ← 有効状態のスクリーンショット
    ├── disabled.png                  ← 無効状態のスクリーンショット
    └── all_states.png                ← 全状態の一覧比較

▼ テスト実行コマンド
# 初回:Goldenファイル(正解画像)を生成
flutter test --update-goldens test/ui/components/primary_button_golden_test.dart

# 以降:画像に差分がないか検証(CIでも実行可能)
flutter test test/ui/components/primary_button_golden_test.dart

セットアップ完了後、対話形式でこのようなテストを自動生成していきます。
何か事前に質問があれば、今のうちにどうぞ。なければ、セットアップを始めましょう。」

Wait for the user's answer → After the answer, proceed to Step 1

Step 1: Project analysis [1/8]

Check the following in the project:

  • test/flutter_test_config.dart Presence of
  • test/helpers/golden_test_helper.dart Presence of
  • pubspec.yaml Font configuration for
  • Location of theme files

Example statement after checking:

「Golden Testの環境をセットアップしますね。まずプロジェクトを確認させてください。

プロジェクト構成を解析しました:
- テストディレクトリ: test/
- テーマファイル: lib/ui/core/themes/theme.dart(検出)
- 使用フォント: Noto Sans JP(assets/fontsから検出)

この認識で合っていますか?」

Wait for the user's answer → After the answer, proceed to Step 2

Step 2: Font configuration check [2/8]

「【Step 2/8】Golden Testではフォントの一貫性が重要です。
プロジェクトで使用しているフォントを教えてください:

1. Noto Sans JP(日本語対応)
2. Roboto(Material Design標準)
3. カスタムフォント(フォント名とパスを教えてください)
4. フォント設定は不要

どれを使用していますか?」

Wait for the user's answer → After the answer, proceed to Step 3

Step 3: Check whether Riverpod is used [3/8]

Based on the project analysis results from Step 1, ask questions using one of the following patterns A/B/C.

A) When Riverpod is not used (no Riverpod-related packages in pubspec.yaml):

「【Step 3/8】プロジェクトでRiverpodを使用していますか?

1. はい - ProviderScopeでラップするヘルパーを追加します
2. いいえ - シンプルなMaterialAppのみで構成します

どちらですか?」

B) When Riverpod is used and an existing test helper (e.g., test/helpers/pump_app.dart) exists:

Always specify the pros and cons of each option and indicate a recommendation.

「【Step 3/8】プロジェクトでRiverpodを使用していることを確認しました。
既存のテストヘルパー({検出したファイルパス})も検出しました。

Golden TestのProviderScope設定について、2つの方針があります:

1. 既存のヘルパーを活用する(推奨)
   ✅ メリット: 既存テストと設定が統一され、Providerのoverrideなどが一箇所で管理できる
   ⚠️ デメリット: 既存ヘルパーの変更がGolden Testにも影響する
   → 既にテストが整備されているプロジェクトにおすすめ

2. Golden Test専用に独立した設定にする
   ✅ メリット: Golden Test固有の設定を自由にカスタマイズでき、他のテストに影響しない
   ⚠️ デメリット: 設定が二重管理になり、変更時に両方を更新する必要がある
   → Golden Test特有のカスタマイズが多い場合におすすめ

迷ったら 1(推奨)を選んでください。どちらにしますか?」

C) When Riverpod is used but no existing test helper exists:

「【Step 3/8】プロジェクトでRiverpodを使用していることを確認しました。
ProviderScopeでラップするGolden Test用ヘルパーを新規作成します。

この方針でよろしいですか?」

Wait for the user's answer → After the answer, proceed to Step 4

Step 4: Theme settings confirmation [4/8]

「【Step 4/8】テストで使用するテーマを教えてください:

1. カスタムテーマを使用(例: AppTheme.light())
2. デフォルトのMaterial Themeを使用

カスタムテーマの場合、インポートパスを教えてください。」

Wait for the user's answer → After the answer, proceed to Step 5

Step 5: Screen size confirmation [5/8]

「【Step 5/8】テスト用のサイズプリセットを設定します。
以下のデフォルト設定でよろしいですか?

コンポーネント用:
- component: 400x100 (単体)
- componentList: 400x400 (複数状態表示)

画面用:
- screenSmall: 375x667 (iPhone SE相当)
- screenMedium: 390x844 (iPhone 14相当)
- screenLarge: 430x932 (iPhone 14 Pro Max相当)

変更したいサイズがあれば教えてください。」

Wait for the user's answer → After the answer, proceed to Step 6

Step 6: Image asset usage confirmation [6/8]

「【Step 6/8】プロジェクトで画像アセットを使用していますか?

1. はい - 画像をテスト環境でロードする設定を追加します
2. いいえ - 画像ローディングの設定は不要です

画像を使用している場合、テストでも正しく表示されるよう設定します。」

Wait for the user's answer → After the answer, proceed to Step 7

Step 7: Test creation granularity confirmation [7/8]

「【Step 7/8】今後のテスト作成時、どの単位でテストを作成しますか?

1. コンポーネント単位 - ボタンやカードなど、再利用可能な部品ごとにテスト
2. 画面単位 - Screen/Pageごとにテスト
3. 都度確認 - テスト作成時に毎回確認する

この設定はプロジェクトのCLAUDE.mdに記録し、以降のテスト作成時に参照します。」

Wait for the user's answer → After the answer, proceed to Step 8 (file generation)

Step 8: File generation [8/8]

After all steps are complete, generate the following files based on the collected information:

  1. test/flutter_test_config.dart

    • Refer to templates/flutter_test_config.dart.md
    • Reflect font settings
    • When image assets are used, add MaterialIcons loading settings
  2. test/helpers/golden_test_helper.dart

    • Refer to templates/golden_test_helper.dart.md
    • When Riverpod is used, also refer to templates/golden_test_helper_riverpod.dart.md
    • Reflect theme and size settings
  3. test/helpers/helpers.dart (barrel file)

    • Export helper files
  4. test/golden_test_issues.md (issue resolution log)

    • Refer to templates/golden_test_issues.md
    • For recording troubleshooting
  5. Append to the project's CLAUDE.md

    • Add a Golden Test settings section
    • Record the test creation granularity settings

Example of appending to CLAUDE.md:

## Golden Test 設定

### テスト作成粒度
- 方針: コンポーネント単位(または画面単位/都度確認)

### プロジェクト固有の注意点
- (問題が発生した場合、ここに記録される)

Example statement after generation:

「以下のファイルを生成しました:

1. test/flutter_test_config.dart
   - グローバルテスト設定
   - フォントローディング
   - アイコンフォントのロード

2. test/helpers/golden_test_helper.dart
   - GoldenTestSizes: サイズプリセット
   - GoldenTestExtension: pumpGoldenWidget(), pumpGoldenWidgetList()
   - GoldenFilePath: パス生成ユーティリティ

3. test/golden_test_issues.md
   - 問題解決ログ(トラブル発生時に記録)

4. CLAUDE.mdに設定を追記しました
   - テスト作成粒度: {選択された粒度}

これでGolden Test環境の準備が完了しました!
試しに1つテストを作成してみますか?」

Mode 2: Test generation

When a Golden Test environment exists and a new test is to be created.

Step 1: Confirmation of test target

「どのウィジェットのGolden Testを作成しますか?

例:
- lib/ui/core/components/primary_button.dart
- lib/ui/features/login/widgets/login_screen.dart

ファイルパスまたはウィジェット名を教えてください。」

Wait for the user's answer

Step 2: Confirmation of test type

Check the test creation granularity settings in CLAUDE.md:

  • "Component unit" → Proceed as a component test
  • "Screen unit" → Proceed as a screen test
  • "Confirm each time" or no setting → Ask the following question
「このウィジェットは以下のどちらですか?(番号でお答えください)

1. コンポーネント(ボタン、カード、入力フィールドなど)
2. 画面(Screen、Pageなど)」

Wait for the user's answer

Step 3: Widget analysis and warning check

Analyze the widget code and check the following:

  1. Detection of network images (Image.network, CachedNetworkImage , etc.)

    • If detected, provide the following guidance:
    「⚠️ ネットワーク画像を検出しました。
    
    Golden Testではネットワーク画像は取得できないため、テスト用にダミー画像で置き換える必要があります。
    
    対応方法:
    1. モック画像プロバイダーを使用
    2. テスト用のアセット画像に差し替え
    
    詳しくは knowledge/common-issues.md の「ネットワーク画像の対応」を参照してください。
    
    このまま進めますか?」
    
  2. Confirmation of Japanese text and fonts

    • When Japanese text is included and the font does not support Japanese, such as Roboto:
    「⚠️ 日本語テキストを検出しましたが、設定されているフォント(Roboto)は日本語に対応していません。
    
    実機ではOSがフォールバックしますが、Golden Testでは日本語が正しく表示されない可能性があります。
    
    対応方法:
    1. Noto Sans JPなど日本語対応フォントを追加
    2. flutter_test_config.dartでフォントをロード
    
    詳しくは knowledge/common-issues.md の「日本語フォントの問題」を参照してください。
    
    このまま進めますか?」
    

Step 4: Widget parameter analysis

Read the code of the target widget and analyze the constructor parameters.

Example statement after analysis:

「PrimaryButtonを解析しました。

コンストラクタパラメータ:
- text: String (必須)
- onPressed: VoidCallback? (オプション)
- icon: Widget? (オプション)

テストしたい状態を選んでください(複数選択可、番号でお答えください):
1. 有効状態(onPressed != null)
2. 無効状態(onPressed == null)
3. アイコン付き
4. 長いテキスト
5. 全状態の比較(一覧表示)

他にテストしたい状態はありますか?」

Wait for the user's answer

Step 5: Test code generation

Generate test code based on the selected state.

  • For components: refer to templates/component_golden_test.dart.md
  • For screens: refer to templates/screen_golden_test.dart.md

Example statement after generation:

「以下のテストファイルを生成しました:

test/ui/core/components/primary_button_golden_test.dart

テストケース:
- 有効状態
- 無効状態
- アイコン付き
- 全状態の比較

Goldenファイルは以下に保存されます:
test/ui/core/components/goldens/components/primary_button/

次のコマンドでGoldenファイルを生成してください:
flutter test --update-goldens test/ui/core/components/primary_button_golden_test.dart

⚠️ もしテスト画像がうまく生成されない場合は、エラー内容を教えてください。一緒に解決していきましょう。」

Mode 3: Test execution/update

Guide how to run the tests.

「Golden Testの実行方法:

■ テスト実行(検証):
flutter test test/ui/core/components/primary_button_golden_test.dart

■ Goldenファイル更新:
flutter test --update-goldens test/ui/core/components/primary_button_golden_test.dart

■ 全Golden Testの実行:
flutter test --tags golden

■ 特定ディレクトリのGolden Test更新:
flutter test --update-goldens test/ui/core/components/

実行しますか?

⚠️ テストが失敗したり、画像が期待通りにならない場合は、エラー内容を教えてください。」

Mode 4: Troubleshooting

Response flow when tests do not go well.

Step 1: Identify the problem

When you receive a report of an error or problem from the user, check the following:

  1. Error message: Specific error details
  2. Difference between expected and actual: What is different
  3. Environment information: Flutter version, OS, etc.

Step 2: Identify the cause and resolve

knowledge/common-issues.md Refer to this and propose the corresponding problem and solution.

Common problems:

  • Font is not displayed → Font loading settings
  • Image is not displayed → Asset loading or mock
  • Fails in CI environment → devicePixelRatio, environment differences
  • Japanese text is garbled → Japanese font settings

Step 3: Record in the problem resolution log

After resolving the problem,test/golden_test_issues.md add a record to:

「問題を解決しました!

今後のために、この問題と解決方法を `test/golden_test_issues.md` に記録しておきますね。

---
## {日付}: {問題の概要}

### 問題
{問題の詳細}

### 原因
{原因の説明}

### 解決方法
{解決手順}

### 今後の注意点
{同様の問題を防ぐためのポイント}
---

これで同じ問題が発生しても、すぐに対応できます。」

Addition to CLAUDE.md (if necessary):

As a project-specific note, also add it to the "Golden Test Settings" section of CLAUDE.md:

### プロジェクト固有の注意点
- {解決した問題の要約と対策}

Template reference

Template files are in the templates/ directory:

Template Purpose
flutter_test_config.dart.md Global test settings
golden_test_helper.dart.md Standard helper
golden_test_helper_riverpod.dart.md Riverpod-compatible helper
component_golden_test.dart.md Component test
screen_golden_test.dart.md Screen test
golden_test_issues.md Problem resolution log

Knowledge reference

When in trouble, refer to the knowledge/ directory:

File Content
golden-test-concepts.md Basic knowledge of Golden Test
common-issues.md Common problems and solutions
best-practices.md Best practices

Output file structure

Generated test files

test/
├── flutter_test_config.dart          # グローバル設定
├── helpers/
│   ├── helpers.dart                  # バレルファイル
│   └── golden_test_helper.dart       # ヘルパー
└── ui/
    └── core/
        └── components/
            ├── primary_button_golden_test.dart
            └── goldens/
                └── components/
                    └── primary_button/
                        ├── enabled.png
                        ├── disabled.png
                        └── all_states.png

Golden file path rules

  • Component: goldens/components/{component_name}/{state_name}.png
  • Screen: goldens/screens/{screen_name}/{state_name}.png

Important notes

  1. Ask one question at a time - Do not ask multiple questions at once
  2. Confirm the user's answer - Confirm before proceeding to the next step
  3. Reflect project-specific settings - Themes, fonts, Riverpod, etc.
  4. Provide guidance on test execution commands - Always communicate how to run it after generation
  5. devicePixelRatio = 1.0 - Required for screenshot consistency