From 72c4db3df2fb9ec7de21d643ddd87b63b72c2570 Mon Sep 17 00:00:00 2001 From: Kota Noda Date: Tue, 24 Nov 2026 01:57:12 +0900 Subject: [PATCH] ja: translate all guide pages and sync with the latest upstream docs --- docs/.vitepress/config.mts | 5 +- docs/ja/guide/misc/rubocop.md | 44 ++-- docs/ja/guide/playbook.md | 143 ++++++----- docs/ja/guide/profilers/event_prof.md | 160 +++++++----- docs/ja/guide/profilers/factory_doctor.md | 75 +++--- docs/ja/guide/profilers/factory_prof.md | 183 +++++++++++--- docs/ja/guide/profilers/memory_prof.md | 48 ++-- docs/ja/guide/profilers/rspec_dissect.md | 80 ++---- docs/ja/guide/profilers/ruby_prof.md | 2 +- docs/ja/guide/profilers/ruby_profilers.md | 165 +++++++----- docs/ja/guide/profilers/stack_prof.md | 2 +- docs/ja/guide/profilers/tag_prof.md | 60 ++--- docs/ja/guide/profilers/tps_prof.md | 139 ++++++++++ .../active_record_shared_connection.md | 20 +- docs/ja/guide/recipes/any_fixture.md | 239 +++++++++--------- docs/ja/guide/recipes/before_all.md | 144 +++++------ docs/ja/guide/recipes/factory_all_stub.md | 28 +- docs/ja/guide/recipes/factory_default.md | 139 ++++++---- docs/ja/guide/recipes/let_it_be.md | 197 +++++++++------ docs/ja/guide/recipes/logging.md | 46 ++-- docs/ja/guide/recipes/rspec_stamp.md | 40 +-- docs/ja/guide/recipes/tests_sampling.md | 20 +- 22 files changed, 1174 insertions(+), 805 deletions(-) create mode 100644 docs/ja/guide/profilers/tps_prof.md diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 35e2408..4577996 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -92,15 +92,16 @@ const jaGuideSidebar = [ ] }, { - text: 'プロファイラー', + text: 'プロファイラ', items: [ - { text: 'Ruby プロファイラー', link: '/ja/guide/profilers/ruby_profilers' }, + { text: 'Ruby プロファイラ', link: '/ja/guide/profilers/ruby_profilers' }, { text: 'Event Profiler', link: '/ja/guide/profilers/event_prof' }, { text: 'Tag Profiler', link: '/ja/guide/profilers/tag_prof' }, { text: 'Factory Doctor', link: '/ja/guide/profilers/factory_doctor' }, { text: 'Factory Profiler', link: '/ja/guide/profilers/factory_prof' }, { text: 'RSpecDissect Profiler', link: '/ja/guide/profilers/rspec_dissect' }, { text: 'Memory Profiler', link: '/ja/guide/profilers/memory_prof' }, + { text: 'TPS Profiler', link: '/ja/guide/profilers/tps_prof' }, ] }, { diff --git a/docs/ja/guide/misc/rubocop.md b/docs/ja/guide/misc/rubocop.md index 14800e8..899aa6b 100755 --- a/docs/ja/guide/misc/rubocop.md +++ b/docs/ja/guide/misc/rubocop.md @@ -1,36 +1,39 @@ -# Custom RuboCop Cops +# RuboCop のカスタム Cop -TestProf comes with the [RuboCop](https://github.com/bbatsov/rubocop) cops that help you write more performant tests. +TestProf には、より高いパフォーマンスのテストを書くことを支援する [RuboCop](https://github.com/rubocop/rubocop) の Cop が付属しています。 -To enable them, require `test_prof/rubocop` in your RuboCop configuration: +これらを有効化するには、RuboCop の設定に `test-prof` を追加してください。 ```yml # .rubocop.yml -require: - - 'test_prof/rubocop' +plugins: + - 'test-prof' ``` -To configure cops to your needs: +もしくは、動的に指定することも可能です。 -```yml -RSpec/AggregateExamples: - AddAggregateFailuresMetadata: false +```sh +bundle exec rubocop --plugin 'test-prof' --only RSpec/AggregateExamples ``` -Or you can just require it dynamically: +> [!NOTE] +> プラグインの仕組みは RuboCop 1.72 以降でサポートされています。それより前のバージョンでは、`plugins` の代わりに `require` を使用してください。 -```sh -bundle exec rubocop -r 'test_prof/rubocop' --only RSpec/AggregateExamples +Cop を自分のニーズに合わせて設定する場合は、以下のようにしてください。 + +```yml +RSpec/AggregateExamples: + AddAggregateFailuresMetadata: false ``` ## RSpec/AggregateExamples -This cop encourages you to use one of the greatest features of the recent RSpec – aggregating failures within an example. +この Cop は、最近の RSpec の強力な機能の一つである「失敗の集約(aggregate_failures)」を example の中で使用することを推奨します。 -Instead of writing one example per assertion, you can group _independent_ assertions together, thus running all setup hooks only once. -That can dramatically increase your performance (by reducing the total number of examples). +アサーションごとに example を書くのではなく、_独立した_ アサーションを一つの example にまとめることで、セットアップのフックを一度だけ実行するようにできます。 +これにより、example の総数が減り、テストのパフォーマンスが劇的に向上することがあります。 -Consider an example: +以下の例を考えます。 ```ruby # bad @@ -48,10 +51,11 @@ it "returns the second page", :aggregate_failures do end ``` -Auto-correction will typically add `:aggregate_failures` to examples, but if your project enables it globally, or selectively by e.g. deriving metadata from file location, you may opt-out of adding it using `AddAggregateFailuresMetadata` config option. +自動修正 (auto-correct) では、通常 example に `:aggregate_failures` を自動的に追加します。 +しかし、プロジェクト全体でグローバルに有効にしている場合や、ファイルの場所からメタデータを導出するなどして選択的に有効にしている場合は、`AddAggregateFailuresMetadata` 設定オプションを使って、追加しないようにできます。 -This cop supports auto-correct feature, so you can automatically refactor you legacy tests! +この Cop は自動修正をサポートしているため、古いテストを自動的にリファクタリングできます! -**NOTE**: `its` examples shown here have been deprecated as of RSpec 3, but users of the [rspec-its gem](https://github.com/rspec/rspec-its) can leverage this cop to cut out that dependency. +**注意**: ここで示した `its` の example は RSpec 3 以降では非推奨になっていますが、[rspec-its gem](https://github.com/rspec/rspec-its) を使用しているユーザーは、この Cop を活用してその依存をなくすことができます。 -**NOTE**: auto-correction of examples using block matchers, such as `change` is deliberately not supported. +**注意**: `change` などのブロックマッチャーを使った example の自動修正は、意図的にサポートしていません。 diff --git a/docs/ja/guide/playbook.md b/docs/ja/guide/playbook.md index 6dbb9da..905c5fb 100755 --- a/docs/ja/guide/playbook.md +++ b/docs/ja/guide/playbook.md @@ -1,31 +1,37 @@ -# Playbook +# プレイブック -This document aims to help you get started with profiling test suites and answers the following questions: which profiles to run first? How do we interpret the results to choose the next steps? Etc. +このプレイブックは、テストスイートのプロファイリングを始める際の手助けを目的としており、「まずどのプロファイラを使うべきか?」「結果をどう解釈し、次のステップをどう決めればよいか?」といった疑問に答えます。 -**NOTE**: This document assumes you're working with a Ruby on Rails application and RSpec testing framework. The ideas can easily be translated into other frameworks. +**注意**:このドキュメントでは、Ruby on RailsアプリケーションとテストフレームワークとしてのRSpecを使用していることを前提としています。これらのアイデアは他のフレームワークにも簡単に応用できます。 -## Step 0. Configuration basics +> 📼 このプレイブックを実際に使っている様子は、[RailsConf 2024 のワークショップ「From slow to go」の録画](https://evilmartians.com/events/from-slow-to-go-rails-test-profiling-hands-on-railsconf-2024)でも確認できます。 -Low-hanging configuration fruits: +## ステップ0. 基本的な設定 -- Disable logging in tests—it's useless. If you really need it, use our [logging utils](./recipes/logging.md). +手軽に改善できる点: + +- テストでのロギング\*を無効にする — 意味がありません。もしログが本当に必要な場合は、[ロギングユーティリティ](./recipes/logging.md)を使用してください。 ```ruby config.logger = ActiveSupport::TaggedLogging.new(Logger.new(nil)) config.log_level = :fatal ``` -- Disable coverage and built-in profiling by default. Use env var to enable it (e.g., `COVERAGE=true`) +- デフォルトではカバレッジと組み込みプロファイリングを無効にする。必要であれば、環境変数を使って有効にしましょう(例:`COVERAGE=true`) + +\* 現代のSSDハードドライブでは、ファイルベースのロギングによるオーバーヘッドはほとんど無視できる程度になっています。それでもなお、どの環境(例:MacOS上のDockerなど)でもテストに影響が出ないように、ロギングは無効にすることを推奨します。 -## Step 1. General profiling +## ステップ1. 全般的なプロファイリング -It helps to identify not-so-low hanging fruits. We recommend using [StackProf](./profilers/stack_prof.md), so you must install it first (if not yet): +手軽には見つからない改善点を特定するのに役立ちます。[StackProf](./profilers/ruby_profilers.md#stackprof) または [Vernier](./profilers/ruby_profilers.md#vernier) の使用をお勧めします。まだインストールしていない場合は、まずインストールする必要があります: ```sh bundle add stackprof +# または +bundle add vernier ``` -Configure Test Prof to generate JSON profiles by default: +TestProfがデフォルトでJSONプロファイルを生成するように設定します: ```ruby TestProf::StackProf.configure do |config| @@ -33,85 +39,88 @@ TestProf::StackProf.configure do |config| end ``` -We recommend using [speedscope](https://www.speedscope.app) to analyze these profiles. +これらのプロファイルを分析するには[speedscope](https://www.speedscope.app)というツールを利用することをお勧めします。 -### Step 1.1. Application boot profiling +### ステップ1.1. アプリケーション起動のプロファイリング ```sh TEST_STACK_PROF=boot rspec ./spec/some_spec.rb ``` -**NOTE:** running a single spec/test is enough for this profiling. +**注意:** このプロファイリングでは、単一のテストを実行するだけでOKです。 -What to look for? Some examples: +注目すべきポイントの例: -- No [Bootsnap](https://github.com/Shopify/bootsnap) used or not configured to cache everything (e.g., YAML files) -- Slow Rails initializers that are not needed in tests. +- [Bootsnap](https://github.com/Shopify/bootsnap)が使用されていない、または全てをキャッシュするように設定されていない(例:YAMLファイル) +- テストでは不要な、遅いRails initializer。Vernier の Rails フック機能は、Rails initializer の分析に特に役立ちます。 -### Step 1.2. Sampling tests profiling +### ステップ1.2. テストのサンプリングプロファイリング -The idea is to run a random subset of tests multiple times to reveal some application-wide problems. You must enable the [sampling feature](./recipes/tests_sampling.md) first: +アイデアとしては、ランダムなテストのサブセットを複数回実行して、アプリケーション全体の問題を明らかにすることです。まず[サンプリング機能](./recipes/tests_sampling.md)を有効にする必要があります: ```rb -# For RSpec in your spec_helper.rb +# RSpecの場合、spec_helper.rbに追加 require "test_prof/recipes/rspec/sample" -# For Minitest in your test_helper.rb +# Minitestの場合、test_helper.rbに追加 require "test_prof/recipes/minitest/sample" ``` -Then run **multiple times** and analyze the obtained flamegraphs: +次に**複数回**実行して、得られたフレームグラフを分析します: ```sh SAMPLE=100 bin/rails test -# or +# または SAMPLE=100 bin/rspec ``` -Common findings: +よくある気づき: -- Encryption calls (`*crypt*`-whatever): relax the settings in the test env -- Log calls: are you sure you disabled logs? -- Databases: maybe there are some low-hanging fruits (like using DatabaseCleaner truncation for every test instead of transactions) -- Network: should not be there for unit tests, inevitable for browser tests; use [Webmock](https://github.com/bblimke/webmock) to disable HTTP calls completely. +- 暗号化呼び出し(`*crypt*`など):テスト環境での設定を緩和する +- ログ呼び出し:ログを無効にしましたか? +- データベース:手軽に改善できる点があるかもしれません(例:全てのテストで、トランザクションの代わりにDatabaseCleanerのトランケーションを使っている場合など) +- ネットワーク:単体テストでは不要ですが、ブラウザテストでは避けられません。[Webmock](https://github.com/bblimke/webmock)を使用して HTTP 呼び出しを完全に無効化しましょう。 -## Step 2. Narrow down the scope +## ステップ2. 範囲を絞り込む -This is an important step for large codebases. We must prioritize quick fixes that bring the most value (time reduction) over dealing with complex, slow tests individually (even if they're the slowest ones). For that, we first identify the **types of tests** contributing the most to the overall run time. +これは、大規模なコードベースにおいて非常に重要なステップです。たとえ最も遅いテストであっても、複雑なものに個別対処するよりは、実行時間の短縮という観点で最も効果の高い、手早く直せる箇所を優先すべきです。 +そのためにまず、全体の実行時間に最も大きく影響している**テストの種類**を特定します。 -We use [TagProf](./profilers/tag_prof.md) for that: +そのために[TagProf](./profilers/tag_prof.md)を使用します: ```sh TAG_PROF=type TAG_PROF_FORMAT=html TAG_PROF_EVENT=sql.active_record,factory.create bin/rspec ``` -Looking at the generated diagram, you can identify the two most time-consuming test types (usually models and/or controllers among them). +生成されたダイアグラムを見ると、最も時間のかかるテストタイプ2つを特定できます(通常、モデルやコントローラーがその中に含まれます)。 -We assume that it's easier to find a common slowness cause for the whole group and fix it than dealing with individual tests. Given that assumption, we continue the process only within the selected group (let's say, models). +グループ全体に共通する遅延の原因を見つけて修正するほうが、個々のテストに個別対応するよりも効率的だと仮定しましょう。 +この前提のもと、選択したグループ(たとえばモデル)内に絞って、分析や対応を進めていきます。 -## Step 3. Specialized profiling +## ステップ3. 専門的なプロファイリング -Within the selected group, we can first perform quick event-based profiling via [EventProf](./profilers/event_prof.md). (Maybe, with sampling enabled as well). +選択したグループ内で、まず[EventProf](./profilers/event_prof.md)を使用して迅速なイベントベースのプロファイリングを実行できます(サンプリングも有効にすることもできます)。 -### Step 3.1. Dependencies configuration +### ステップ3.1. 依存関係の設定 -At this point, we may identify some misconfigured or misused dependencies/gems. Common examples: +この時点で、設定ミスや誤った使い方をされている依存関係や gem を特定できる場合があります。 +よくある例: -- Inlined Sidekiq jobs: +- インラインで実行されるSidekiqジョブ ```sh EVENT_PROF=sidekiq.inline bin/rspec spec/models ``` -- Wisper broadcasts ([patch required](https://gist.github.com/palkan/aa7035cebaeca7ed76e433981f90c07b)): +- Wisperブロードキャスト([パッチが必要](https://gist.github.com/palkan/aa7035cebaeca7ed76e433981f90c07b)) ```sh EVENT_PROF=wisper.publisher.broadcast bin/rspec spec/models ``` -- PaperTrail logs creation: +- PaperTrailのログ作成 -Enable custom profiling: +カスタムプロファイリングを有効にします: ```rb TestProf::EventProf.monitor(PaperTrail::RecordTrail, "paper_trail.record", :record_create) @@ -119,85 +128,87 @@ TestProf::EventProf.monitor(PaperTrail::RecordTrail, "paper_trail.record", :reco TestProf::EventProf.monitor(PaperTrail::RecordTrail, "paper_trail.record", :record_update) ``` -Run tests: +その上でテストを実行します: ```sh EVENT_PROF=paper_trail.record bin/rspec spec/models ``` -See [the Sidekiq example](https://evilmartians.com/chronicles/testprof-a-good-doctor-for-slow-ruby-tests#background-jobs) on how to quickly fix such problems using [RSpecStamp](./recipes/rspec_stamp.md). +[RSpecStamp](./recipes/rspec_stamp.md)を使用してこのような問題を素早く修正する方法については、[Sidekiqの例](https://evilmartians.com/chronicles/testprof-a-good-doctor-for-slow-ruby-tests#background-jobs)を参照してください。 -### Step 3.2. Data generation +### ステップ3.2. データ生成 -Identify the slowest tests based on the amount of time spent in the database or factories (if any): +データベースやファクトリ(使用している場合)関連で費やされた時間に基づき、最も遅いテストを特定します: ```sh -# Database interactions +# データベースとのやり取り EVENT_PROF=sql.active_record bin/rspec spec/models -# Factories +# ファクトリ EVENT_PROF=factory.create bin/rspec spec/models ``` -Now, we can narrow our scope further to the top 10 files from the generated reports. If you use factories, use the `factory.create` report. +これで、生成されたレポートから上位10ファイルにさらに範囲を絞ることができます。ファクトリを使用している場合は、`factory.create`レポートを使用してください。 -**TIP:** In RSpec, you can mark the slowest examples with a custom tag automatically using the following command: +**ヒント:** RSpecでは、次のコマンドを使用して、最も遅い example をカスタムタグで自動的にマークできます: ```sh -EVENT_PROF=factory.create EVEN_PROF_STAMP=slow:factory bin/rspec spec/models +EVENT_PROF=factory.create EVENT_PROF_STAMP=slow:factory bin/rspec spec/models ``` -## Step 4. Factories usage +## ステップ4. ファクトリの使用 -Identify the most used factories among the `slow:factory` tests: +`slow:factory`テストの中で最も使用されているファクトリを特定します: ```sh FPROF=1 bin/rspec --tag slow:factory ``` -If you see some factories used much more times than the total number of examples, you deal with _factory cascades_. +example の総数よりもはるかに多くの回数使用されているファクトリが見つかった場合、_ファクトリカスケード_ が起きています。 -Visualize the cascades: +カスケードを視覚化します: ```sh FPROF=flamegraph bin/rspec --tag slow:factory ``` -The visualization should help to identify the factories to be fixed. You find possible solutions in [this post](https://evilmartians.com/chronicles/testprof-2-factory-therapy-for-your-ruby-tests-rspec-minitest). +この視覚化は、修正すべきファクトリを特定するのに役立ちます。[この記事](https://evilmartians.com/chronicles/testprof-2-factory-therapy-for-your-ruby-tests-rspec-minitest)で解決策を見つけることができます。 -### Step 4.1. Factory defaults +### ステップ4.1. ファクトリデフォルト -One option to fix cascades produced by model associations is to use [factory defaults](./recipes/factory_default.md). To estimate the potential impact and identify factories to apply this pattern to, run the following profiler: +モデルの関連付けによって生成されるカスケードを修正する一つの選択肢は、[factory defaults](./recipes/factory_default.md)を使用することです。潜在的な影響を評価し、このパターンを適用するファクトリを特定するには、次のプロファイラを実行します: ```sh FACTORY_DEFAULT_PROF=1 bin/rspec --tag slow:factory ``` -Try adding `create_default` and measure the impact: +`create_default`を追加して影響を測定してみてください: ```sh FACTORY_DEFAULT_SUMMARY=1 bin/rspec --tag slow:factory -# More hits — better +# ヒット数が多いほど良い FactoryDefault summary: hit=11 miss=3 ``` -### Step 4.2. Factory fixtures +### ステップ4.2. ファクトリフィクスチャ -Back to the `FPROF=1` report, see if you have some records created for every example (typically, `user`, `account`, `team`). Consider replacing them with fixtures using [AnyFixture](./recipes/any_fixture.md). +`FPROF=1`レポートに戻り、すべての example で作成されるレコードがあるか確認します(通常、`user`、`account`、`team`など)。[AnyFixture](./recipes/any_fixture.md)を使用してフィクスチャに置き換えることを検討してください。 -## Step 5. Reusable setup +## ステップ5. 再利用可能なセットアップ -It's common to have the same setup shared across multiple examples. You can measure the time spent in `let` / `before` compared to the actual example time using [RSpecDissect](./profilers/rspec_dissect.md): +複数の example で同じセットアップが共有されていることはよくあります。[RSpecDissect](./profilers/rspec_dissect.md)を使用して、実際の example の時間と比較して`let` / `before`で費やされた時間を測定できます: ```sh RD_PROF=1 bin/rspec ``` -Take a look at the slowest groups and try to replace `let`/`let!` with [let_it_be](./recipes/let_it_be.md) and `before` with [before_all](./recipes/before_all.md). +最も遅いグループを確認し、`let`/`let!`を[let_it_be](./recipes/let_it_be.md)に、`before`を[before_all](./recipes/before_all.md)に置き換えることを検討してください。 + +**重要:** Knapsack Proユーザーは、example 単位の分散が`let_it_be` / `before_all`の効果を打ち消してしまうことに注意してください。ファイル単位の分散に切り替えた上で、ファイルを小さく保つ必要があります。これがTestProfの最適化の効果を最大化する方法です。 + +## 結論 -**IMPORTANT:** Knapsack Pro users must be aware that per-example balancing eliminates the positive effect of using `let_it_be` / `before_all`. You must switch to per-file balancing while at the same time keeping your files small—that's how you can maximize the effect of using Test Prof optimizations. +上記のステップを特定のテストグループに適用し終える頃には、あなたのコードベースに合った最適化のパターンと技法ができあがっているはずです。あとは、それらを他のグループにも広げていくだけです。がんばってください! -## Conclusion -After applying the steps above to a given group of tests, you should develop the patterns and techniques optimized for your codebase. Then, all you need is to extrapolate them to other groups. Good luck! diff --git a/docs/ja/guide/profilers/event_prof.md b/docs/ja/guide/profilers/event_prof.md index bacaee0..b771a5a 100755 --- a/docs/ja/guide/profilers/event_prof.md +++ b/docs/ja/guide/profilers/event_prof.md @@ -1,10 +1,10 @@ # EventProf -EventProf collects instrumentation (such as ActiveSupport::Notifications) metrics during your test suite run. +EventProf は、テストスイートの実行中に、計測の仕組み (ActiveSupport::Notifications など) から得られるメトリクスを収集します。 -It works very similar to `rspec --profile` but can track arbitrary events. +`rspec --profile` とよく似た動きをしますが、任意のイベントを追跡できます。 -Example output: +出力例: ```sh [TEST PROF INFO] EventProf results for sql.active_record @@ -28,22 +28,22 @@ fails (./spec/shared_examples/controllers/invalid_examples.rb:3) – 00:00.007 ( ``` -## Instructions +## 使い方 -Currently, EventProf supports only ActiveSupport::Notifications +現在、EventProf がサポートしているのは ActiveSupport::Notifications のみです。 -To activate EventProf with: +EventProf を有効にする方法は次のとおりです。 ### RSpec -Use `EVENT_PROF` environment variable set to event name: +環境変数 `EVENT_PROF` にイベント名を指定します。 ```sh -# Collect SQL queries stats for every suite and example +# すべてのスイートと example について SQL クエリの統計を収集する EVENT_PROF='sql.active_record' rspec ... ``` -You can track multiple events simultaneously: +複数のイベントを同時に追跡することもできます。 ```sh EVENT_PROF='sql.active_record,perform.active_job' rspec ... @@ -51,50 +51,46 @@ EVENT_PROF='sql.active_record,perform.active_job' rspec ... ### Minitest -Use `EVENT_PROF` environment variable set to event name: +Minitest 6 以降では、まずテストヘルパーに `Minitest.load :test_prof` を追加して、TestProf プラグインを有効にする必要があります。 + +環境変数 `EVENT_PROF` にイベント名を指定します。 ```sh -# Collect SQL queries stats for every suite and example +# すべてのスイートと example について SQL クエリの統計を収集する EVENT_PROF='sql.active_record' rake test ``` -or use CLI options as well: +CLI オプションを使うこともできます。 ```sh -# Run a specific file using CLI option +# CLI オプションを使って特定のファイルを実行する ruby test/my_super_test.rb --event-prof=sql.active_record -# Show the list of possible options: +# 使用できるオプションの一覧を表示する ruby test/my_super_test.rb --help ``` -### Using with Minitest::Reporters +### Minitest::Reporters と併用する -If you're using `Minitest::Reporters` in your project you have to explicitly declare it -in your test helper file: +プロジェクトで `Minitest::Reporters` を使用している場合は、テストヘルパーのファイルで明示的に宣言する必要があります。 ```sh require 'minitest/reporters' Minitest::Reporters.use! [YOUR_FAVORITE_REPORTERS] ``` -#### NOTICE +#### 注意事項 -When you have `minitest-reporters` installed as a gem but not declared in your `Gemfile` -make sure to always prepend your test run command with `bundle exec` (but we sure that you always do it). -Otherwise, you'll get an error caused by Minitest plugin system, which scans all the entries in the -`$LOAD_PATH` for any `minitest/*_plugin.rb`, thus initialization of `minitest-reporters` plugin which is -available in that case doesn't happens correctly. +`minitest-reporters` が gem としてインストールされているものの `Gemfile` には宣言されていない場合は、テストの実行コマンドの前に必ず `bundle exec` を付けてください (いつもそうしているとは思いますが)。 +そうしないと、Minitest のプラグインシステムが原因でエラーになります。このシステムは `$LOAD_PATH` 内のすべてのエントリから `minitest/*_plugin.rb` を探すため、その場合に利用可能となる `minitest-reporters` プラグインの初期化が正しく行われません。 -See [Rails guides](http://guides.rubyonrails.org/active_support_instrumentation.html) -for the list of available events if you're using Rails. +Rails を使用している場合、利用できるイベントの一覧は [Rails ガイド](http://guides.rubyonrails.org/active_support_instrumentation.html) を参照してください。 -If you're using [rom-rb](http://rom-rb.org) you might be interested in profiling `'sql.rom'` event. +[rom-rb](http://rom-rb.org) を使用している場合は、`'sql.rom'` イベントのプロファイリングが役に立つかもしれません。 -## Configuration +## 設定 -By default, EventProf collects information only about top-level groups (aka suites), -but you can also profile individual examples. Just set the configuration option: +デフォルトでは、EventProf はトップレベルのグループ (いわゆるスイート) についての情報のみを収集しますが、個々の example をプロファイリングすることもできます。次の設定オプションを指定するだけです。 ```ruby TestProf::EventProf.configure do |config| @@ -102,37 +98,52 @@ TestProf::EventProf.configure do |config| end ``` -Or provide the `EVENT_PROF_EXAMPLES=1` env variable. +あるいは、環境変数 `EVENT_PROF_EXAMPLES=1` を指定します。 -Another useful configuration parameter – `rank_by`. It's responsible for sorting stats – -either by the time spent in the event or by the number of occurrences: +もうひとつの便利な設定パラメータが `rank_by` です。これは統計の並び順を決めるもので、イベントに費やした時間、または発生回数のどちらかで並べ替えます。 ```sh EVENT_PROF_RANK=count EVENT_PROF='instantiation.active_record' be rspec ``` -See [event_prof.rb](https://github.com/test-prof/test-prof/tree/master/lib/test_prof/event_prof.rb) for all available configuration options and their usage. +## フォーマット + +デフォルトでは、EventProf は結果を標準出力に表示します。環境変数 `EVENT_PROF_FORMAT` (または `config.format`) を設定すると、JSON として出力することもできます。 + +```sh +EVENT_PROF='sql.active_record' EVENT_PROF_FORMAT=json rspec ... +``` + +JSON の成果物は `tmp/test_prof/event-prof.json` に書き出されます (パスはグローバルの `output_dir` オプションで変更できます)。 + +Minitest では、対応する CLI オプションを使用できます。 + +```sh +ruby test/my_super_test.rb --event-prof=sql.active_record --event-prof-format=json +``` + +利用できるすべての設定オプションとその使い方については、[event_prof.rb](https://github.com/test-prof/test-prof/tree/master/lib/test_prof/event_prof.rb) を参照してください。 -## Using with RSpecStamp +## RSpecStamp と併用する -EventProf can be used with [RSpec Stamp](../recipes/rspec_stamp.md) to automatically mark _slow_ examples with custom tags. For example: +EventProf を [RSpec Stamp](../recipes/rspec_stamp.md) と併用すると、_遅い_ example にカスタムタグを自動で付けることができます。たとえば次のようにします。 ```sh EVENT_PROF="sql.active_record" EVENT_PROF_STAMP="slow:sql" rspec ... ``` -After running the command above the slowest example groups (and examples if configured) would be marked with the `slow: :sql` tag. +上のコマンドを実行すると、最も遅い example group (設定していれば example も) に `slow: :sql` タグが付きます。 -## Custom Instrumentation +## カスタムの計測 -To use EventProf with your instrumentation engine just complete the two following steps: +EventProf を独自の計測エンジンと一緒に使うには、次の 2 つの手順を行うだけです。 -- Add a wrapper for your instrumentation: +- 計測のラッパーを追加します。 ```ruby -# Wrapper over your instrumentation +# 独自の計測に対するラッパー module MyEventsWrapper - # Should contain the only one method + # メソッドはこの 1 つだけを持つこと def self.subscribe(event) raise ArgumentError, "Block is required!" unless block_given? @@ -143,7 +154,7 @@ module MyEventsWrapper end ``` -- Set instrumenter in the config: +- 設定で instrumenter を指定します。 ```ruby TestProf::EventProf.configure do |config| @@ -151,73 +162,93 @@ TestProf::EventProf.configure do |config| end ``` -## Custom Events +## カスタムイベント ### `"factory.create"` -FactoryGirl provides its own instrumentation ('factory_girl.run_factory'); but there is a caveat – it fires an event every time a factory is used, even when we use factory for nested associations. Thus it's not possible to calculate the total time spent in factories due to the double calculation. +FactoryBot は独自の計測 ('factory_bot.run_factory') を提供していますが、注意点があります。ネストした関連のためにファクトリを使う場合も含め、ファクトリが使われるたびにイベントが発火するのです。そのため二重に計上されてしまい、ファクトリに費やした合計時間を算出できません。 -EventProf comes with a little patch for FactoryGirl which provides instrumentation only for top-level `FactoryGirl.create` calls. It is loaded automatically if you use `"factory.create"` event: +EventProf には FactoryBot 向けの小さなパッチが付属しており、トップレベルの `FactoryBot.create` の呼び出しだけを計測します。`"factory.create"` イベントを使うと自動で読み込まれます。 ```sh EVENT_PROF=factory.create bundle exec rspec ``` -Also supports Fabrication (tracks implicit and explicit `Fabricate.create` calls). +Fabrication もサポートしています (暗黙的・明示的な `Fabricate.create` の呼び出しを追跡します)。 ### `"sidekiq.jobs"` -Collects statistics about Sidekiq jobs that have been run inline: +インラインで実行された Sidekiq ジョブの統計を収集します。 ```sh EVENT_PROF=sidekiq.jobs bundle exec rspec ``` -**NOTE**: automatically sets `rank_by` to `count` ('cause it doesn't make sense to collect the information about time spent – see below). +**注意**: `rank_by` は自動的に `count` に設定されます (費やした時間の情報を集めても意味がないためです。下記を参照してください)。 ### `"sidekiq.inline"` -Collects statistics about Sidekiq jobs that have been run inline (excluding nested jobs): +インラインで実行された Sidekiq ジョブの統計を収集します (ネストしたジョブは除きます)。 ```sh EVENT_PROF=sidekiq.inline bundle exec rspec ``` -Use this event to profile the time spent running Sidekiq jobs. +Sidekiq ジョブの実行に費やした時間をプロファイリングするには、このイベントを使用してください。 + +### `"callback.run"` + +[ActiveSupport のコールバック](https://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html) の呼び出し (`before`/`after`) の統計を収集します。 + +```sh +EVENT_PROF=callback.run bundle exec rspec +``` + +`ActiveSupport::Callbacks` が読み込まれている必要があります (Rails 経由、または `require "active_support/callbacks"` など)。 + +レポートにはコールバックごとの内訳が含まれ、それぞれの時間と呼び出し回数が表示されます (`kind_name filter (Owner)`)。各コールバックイベントは `{label: "..."}` という形式のペイロードを持ち、イベントはそのラベルごとにまとめられます。 + +``` + before_save normalize (Order) → 00:00.012 (42) + after_save audit (Order) → 00:00.008 (42) +``` + +**注意:** 追跡されるのは `before` と `after` のコールバックのみです。`around` コールバックは計測されません。 -## Profile arbitrary methods +## 任意のメソッドをプロファイリングする -You can also add your custom events to profile specific methods (for example, after figuring out some hot calls with [RubyProf](./ruby_prof.md) or [StackProf](./stack_prof.md)). +特定のメソッドをプロファイリングするために、独自のカスタムイベントを追加することもできます (たとえば、[RubyProf](./ruby_prof.md) や [StackProf](./stack_prof.md) でボトルネックになっている呼び出しを突き止めた後など)。 -For example, having a class doing some heavy work: +たとえば、重い処理を行うクラスがあるとします。 ```ruby class Work def do_smth(*args) - # do something + # 何らかの処理を行う end end ``` -You can profile it by adding a _monitor_: +_モニター_ を追加することでプロファイリングできます。 ```ruby -# provide a class, event name and methods to monitor +# クラス、イベント名、監視するメソッドを指定する TestProf::EventProf.monitor(Work, "my.work", :do_smth) ``` -And then run EventProf as usual: +あとは、いつもどおり EventProf を実行します。 ```sh EVENT_PROF=my.work bundle exec rake test ``` -You can also provide additional options: +追加のオプションを指定することもできます。 -- `top_level: true | false` (defaults to `false`): defines whether you want to take into account only top-level invocations and ignore nested triggers of this event (that's how "factory.create" is [implemented](https://github.com/test-prof/test-prof/blob/master/lib/test_prof/event_prof/custom_events/factory_create.rb)) -- `guard: Proc` (defaults to `nil`): provide a Proc which could prevent from triggering an event: the method is instrumented only if `guard` returns `true`; `guard` is executed using `instance_exec` and the method arguments are passed to it. +- `top_level: true | false` (デフォルトは `false`): トップレベルの呼び出しだけを対象とし、このイベントのネストした発火を無視するかどうかを指定します ("factory.create" はこの方法で[実装](https://github.com/test-prof/test-prof/blob/master/lib/test_prof/event_prof/custom_events/factory_create.rb)されています) +- `guard: Proc` (デフォルトは `nil`): イベントの発火を抑止できる Proc を指定します。`guard` が `true` を返した場合にのみメソッドが計測されます。`guard` は `instance_exec` で実行され、メソッドの引数が渡されます。 +- `payload: Proc` (デフォルトは `nil`): `Hash` を返す Proc を指定すると、各イベントにペイロードを付与できます (`ActiveSupport::Notifications` のペイロードとしてそのまま渡されます)。Hash に `:label` キーが含まれている場合、同じラベルを持つイベントが内訳として集計されます ([`"callback.run"`](#callbackrun) を参照)。Proc は `instance_exec` で評価され、メソッドの引数が渡されます。 -For example: +たとえば次のようにします。 ```ruby TestProf::EventProf.monitor( @@ -229,16 +260,15 @@ TestProf::EventProf.monitor( ) ``` -You can add monitors _on demand_ (i.e. only when you want to track the specified event) by wrapping -the code in `TestProf::EventProf::CustomEvents.register` method: +コードを `TestProf::EventProf::CustomEvents.register` メソッドで囲むと、モニターを _必要なときだけ_ (つまり、指定したイベントを追跡したいときにのみ) 追加できます。 ```ruby TestProf::EventProf::CustomEvents.register("my.work") do TestProf::EventProf.monitor(Work, "my.work", :do_smth) end -# Then call `activate_all` with the provided event +# その後、指定されたイベントを渡して `activate_all` を呼び出す TestProf::EventProf::CustomEvents.activate_all(TestProf::EventProf.config.event) ``` -The block is evaluated only if the specified event is enabled with EventProf. +このブロックは、指定したイベントが EventProf で有効になっている場合にのみ評価されます。 diff --git a/docs/ja/guide/profilers/factory_doctor.md b/docs/ja/guide/profilers/factory_doctor.md index 5a23af9..ab54128 100755 --- a/docs/ja/guide/profilers/factory_doctor.md +++ b/docs/ja/guide/profilers/factory_doctor.md @@ -1,16 +1,16 @@ # Factory Doctor -One common bad pattern that slows our tests down is unnecessary database manipulation. Consider a _bad_ example: +テストを遅くするよくある悪いパターンのひとつが、不要なデータベース操作です。次の _悪い_ 例を考えてみましょう。 ```ruby -# with FactoryBot/FactoryGirl +# FactoryBot の場合 it "validates name presence" do user = create(:user) user.name = "" expect(user).not_to be_valid end -# with Fabrication +# Fabrication の場合 it "validates name presence" do user = Fabricate(:user) user.name = "" @@ -18,17 +18,17 @@ it "validates name presence" do end ``` -Here we create a new user record, run all callbacks and validations and save it to the database. We don't need all these! Here is a _good_ example: +ここでは新しい user レコードを作成し、すべてのコールバックとバリデーションを実行して、データベースに保存しています。これらはどれも必要ありません! 次が _良い_ 例です。 ```ruby -# with FactoryBot/FactoryGirl +# FactoryBot の場合 it "validates name presence" do user = build_stubbed(:user) user.name = "" expect(user).not_to be_valid end -# with Fabrication +# Fabrication の場合 it "validates name presence" do user = Fabricate.build(:user) user.name = "" @@ -36,11 +36,11 @@ it "validates name presence" do end ``` -Read more about [`build_stubbed`](https://robots.thoughtbot.com/use-factory-girls-build-stubbed-for-a-faster-test). +詳しくは [`build_stubbed`](https://thoughtbot.com/blog/use-factory-bots-build-stubbed-for-a-faster-test) についての記事を参照してください。 -FactoryDoctor is a tool that helps you identify such _bad_ tests, i.e. tests that perform unnecessary database queries. +FactoryDoctor は、このような _悪い_ テスト、つまり不要なデータベースクエリを実行しているテストを特定するのに役立つツールです。 -Example output: +出力例: ```sh [TEST PROF INFO] FactoryDoctor report @@ -53,15 +53,14 @@ User (./spec/models/user_spec.rb:3) (3 records created, 00:00.628) validates email (./spec/user_spec.rb:8) – 2 records created, 00:00.514 ``` -**NOTE**: have you noticed the "potentially" word? Unfortunately, FactoryDoctor is not a -magician (it's still learning) and sometimes it produces false negatives and false positives too. +**注意**: 「potentially (可能性のある)」という言葉に気づきましたか? 残念ながら、FactoryDoctor は魔法使いではなく (まだ勉強中です)、偽陰性や偽陽性を出すこともあります。 -Please, submit an [issue](https://github.com/test-prof/test-prof/issues) if you found a case which makes FactoryDoctor fail. +FactoryDoctor がうまく動かないケースを見つけたら、ぜひ [issue](https://github.com/test-prof/test-prof/issues) を登録してください。 -You can also tell FactoryDoctor to ignore specific examples/groups. Just add the `:fd_ignore` tag to it: +特定の example や group を無視するよう FactoryDoctor に伝えることもできます。`:fd_ignore` タグを付けるだけです。 ```ruby -# won't be reported as offense +# 違反として報告されない it "is ignored", :fd_ignore do user = create(:user) user.name = "" @@ -69,50 +68,52 @@ it "is ignored", :fd_ignore do end ``` -## Instructions +## 使い方 -FactoryDoctor supports: +FactoryDoctor は次のものをサポートしています。 -- FactoryGirl/FactoryBot +- FactoryBot - Fabrication. ### RSpec -To activate FactoryDoctor use `FDOC` environment variable: +FactoryDoctor を有効にするには、環境変数 `FDOC` を使用します。 ```sh FDOC=1 rspec ... ``` -### Using with RSpecStamp +### RSpecStamp と併用する -FactoryDoctor can be used with [RSpec Stamp](../recipes/rspec_stamp.md) to automatically mark _bad_ examples with custom tags. For example: +FactoryDoctor を [RSpec Stamp](../recipes/rspec_stamp.md) と併用すると、_悪い_ example にカスタムタグを自動で付けることができます。たとえば次のようにします。 ```sh FDOC=1 FDOC_STAMP="fdoc:consider" rspec ... ``` -After running the command above all _potentially_ bad examples would be marked with the `fdoc: :consider` tag. +上のコマンドを実行すると、悪い _可能性のある_ example のすべてに `fdoc: :consider` タグが付きます。 ### Minitest -To activate FactoryDoctor use `FDOC` environment variable: +Minitest 6 以降では、まずテストヘルパーに `Minitest.load :test_prof` を追加して、TestProf プラグインを有効にする必要があります。 + +FactoryDoctor を有効にするには、環境変数 `FDOC` を使用します。 ```sh FDOC=1 ruby ... ``` -or use CLI option as shown below: +あるいは、次のように CLI オプションを使用します。 ```sh ruby ... --factory-doctor ``` -The same option to force Factory Doctor to ignore specific examples is also available for Minitest. -Just use `fd_ignore` inside your example: +特定の example を Factory Doctor に無視させるオプションは、Minitest でも同じように使えます。 +example の中で `fd_ignore` を使うだけです。 ```ruby -# won't be reported as offense +# 違反として報告されない it "is ignored" do fd_ignore @@ -121,33 +122,29 @@ it "is ignored" do end ``` -### Using with Minitest::Reporters +### Minitest::Reporters と併用する -If you're using `Minitest::Reporters` in your project you have to explicitly declare it -in your test helper file: +プロジェクトで `Minitest::Reporters` を使用している場合は、テストヘルパーのファイルで明示的に宣言する必要があります。 ```sh require 'minitest/reporters' Minitest::Reporters.use! [YOUR_FAVORITE_REPORTERS] ``` -**NOTE**: When you have `minitest-reporters` installed as a gem but not declared in your `Gemfile` -make sure to always prepend your test run command with `bundle exec` (but we sure that you always do it). -Otherwise, you'll get an error caused by Minitest plugin system, which scans all the entries in the -`$LOAD_PATH` for any `minitest/*_plugin.rb`, thus initialization of `minitest-reporters` plugin which is -available in that case doesn't happens correctly. +**注意**: `minitest-reporters` が gem としてインストールされているものの `Gemfile` には宣言されていない場合は、テストの実行コマンドの前に必ず `bundle exec` を付けてください (いつもそうしているとは思いますが)。 +そうしないと、Minitest のプラグインシステムが原因でエラーになります。このシステムは `$LOAD_PATH` 内のすべてのエントリから `minitest/*_plugin.rb` を探すため、その場合に利用可能となる `minitest-reporters` プラグインの初期化が正しく行われません。 -## Configuration +## 設定 -The following configuration parameters are available (showing defaults): +次の設定パラメータを利用できます (デフォルト値を示しています)。 ```ruby TestProf::FactoryDoctor.configure do |config| - # Which event to track within test example to consider them "DB-dirty" + # example を「DB を汚した」とみなすために、example 内で追跡するイベント config.event = "sql.active_record" - # Consider result "good" if the time in DB is less then the threshold + # DB での所要時間がしきい値より短ければ、結果を「良い」とみなす config.threshold = 0.01 end ``` -You can use the corresponding env variables as well: `FDOC_EVENT` and `FDOC_THRESHOLD`. +対応する環境変数 `FDOC_EVENT` と `FDOC_THRESHOLD` も使用できます。 diff --git a/docs/ja/guide/profilers/factory_prof.md b/docs/ja/guide/profilers/factory_prof.md index abdacb7..c956438 100755 --- a/docs/ja/guide/profilers/factory_prof.md +++ b/docs/ja/guide/profilers/factory_prof.md @@ -1,8 +1,8 @@ # FactoryProf -FactoryProf tracks your factories usage statistics, i.e. how often each factory has been used. +FactoryProf は、ファクトリの使用状況の統計、つまり各ファクトリがどれだけ使われたかを追跡します。 -Example output: +出力例: ```sh [TEST PROF INFO] Factories usage @@ -12,87 +12,192 @@ Total top-level: 10286 Total time: 04:31.222 (out of 07.16.124) Total uniq factories: 119 - total top-level total time time per call top-level time name - 6091 2715 115.7671s 0.0426s 50.2517s user - 2142 2098 93.3152s 0.0444s 92.1915s post - ... + name total top-level total time time per call top-level time + + user 6091 2715 115.7671s 0.0426s 50.2517s + post 2142 2098 93.3152s 0.0444s 92.1915s + ... ``` -It shows both the total number of the factory runs and the number of _top-level_ runs, i.e. not during another factory invocation (e.g. when using associations.) +ファクトリの実行回数の合計と、_トップレベル_ での実行回数、つまり別のファクトリの呼び出しの最中 (関連を使う場合など) ではない実行の回数の両方が表示されます。 -It also shows the time spent generating records with factories and the amount of time taken per factory call. +また、ファクトリでのレコード生成に費やした時間と、ファクトリの呼び出し 1 回あたりの所要時間も表示されます。 -**NOTE**: FactoryProf only tracks the database-persisted factories. In case of FactoryGirl/FactoryBot these are the factories provided by using `create` strategy. In case of Fabrication - objects that created using `create` method. +**注意**: FactoryProf が追跡するのは、レコードをデータベースに永続化するファクトリの呼び出しのみです。FactoryBot の場合は `create` ストラテジー、Fabrication の場合は `create` メソッドで作られるオブジェクトが該当します。 -## Instructions +## 使い方 -FactoryProf can be used with FactoryGirl/FactoryBot or Fabrication - application can be bundled with both gems at the same time. +FactoryProf は FactoryBot と Fabrication のどちらでも使用できます。アプリケーションに両方の gem が同時に入っていても構いません。 -To activate FactoryProf use `FPROF` environment variable: +FactoryProf を有効にするには、環境変数 `FPROF` を使用します。 ```sh -# Simple profiler +# シンプルなプロファイラ FPROF=1 rspec -# or +# または FPROF=1 bundle exec rake test ``` -### [_Nate Heckler_](https://twitter.com/nateberkopec/status/1389945187766456333) mode +### [_Nate Heckler_](https://twitter.com/nateberkopec/status/1389945187766456333) モード -To encourage you to fix your factories as soon as possible, we also have a special _Nate heckler_ mode. +できるだけ早くファクトリを直す気になってもらうために、特別な _Nate heckler_ モードも用意しています。 -Drop this into your `rails_helper.rb` or `test_helper.rb`: +次の 1 行を `rails_helper.rb` または `test_helper.rb` に追加してください。 ```ruby require "test_prof/factory_prof/nate_heckler" ``` -And for every test run see the overall factories usage: +すると、テストを実行するたびにファクトリ全体の使用状況が表示されます。 ```sh [TEST PROF INFO] Time spent in factories: 04:31.222 (54% of total time) ``` -### Exporting profile results to a JSON file +### バリエーション + +環境変数 `FPROF_VARS=1` を指定するか、コードで有効にすることで、_バリエーション_ (trait やオーバーライドなど) の情報をレポートに追加することもできます。 -FactoryProf can save profile results as a JSON file. +```ruby +TestProf::FactoryProf.configure do |config| + config.include_variations = true +end +``` -To use this feature, set the `FPROF` environment variable to `json`: +たとえば次のようになります。 + +```sh +$ FPROF=1 FPROF_VARS=1 bin/rails test + +... + +[TEST PROF INFO] Factories usage + +Total: 15285 +Total top-level: 10286 +Total time: 04:31.222 (out of 07.16.124) +Total uniq factories: 119 + + name total top-level total time time per call top-level time + + user 6091 2715 115.7671s 0.0426s 50.251s + - 5243 1989 84.231s 0.0412s 34.321s + .admin 823 715 15.767s 0.0466s 5.257s + [name,role] 25 11 7.671s 0.0666s 1.257s + post 2142 2098 93.315s 0.0444s 92.191s + _ 2130 2086 87.685s 0.0412s 88.191s + .draft[tags] 12 12 9.315s 0.164s 42.115s + ... +``` + +上の例では、`-` は trait もオーバーライドもないファクトリ (例: `create(:user)`)、`.xxx` は trait、`[a,b]` はオーバーライドのキーを表します。たとえば `create(:user, :admin)` は `.admin` というバリエーションになり、`create(:post, :draft, tags: ["a"])` は `.draft[tags]` になります。 + +#### バリエーションの上限の設定 + +FactoryProf を実行すると、長すぎるバリエーションが出力に含まれ、表示が崩れることがあります。 + +これを避けて最も重要な統計に集中するために、バリエーションの上限値を指定できます。trait やオーバーライドの数が上限を超えるバリエーションは、代わりに特別な ID (`[...]`) で表示されます。 + +バリエーションの上限パラメータを使うには、環境変数 `FPROF_VARIATIONS_LIMIT` に `N` を設定します (`N` は上限の数です)。 + +```sh +FPROF=1 FPROF_VARIATIONS_LIMIT=5 rspec + +# または +FPROF=1 FPROF_VARIATIONS_LIMIT=5 bundle exec rake test +``` + +あるいは、`FactoryProf` の設定で上限のパラメータを指定することもできます。 + +```ruby +TestProf::FactoryProf.configure do |config| + config.variations_limit = 5 +end +``` + +### プロファイル結果を JSON ファイルに書き出す + +FactoryProf は、プロファイル結果を JSON ファイルとして保存できます。 + +この機能を使うには、環境変数 `FPROF` に `json` を設定します。 ```sh FPROF=json rspec -# or +# または FPROF=json bundle exec rake test ``` -Example output: +出力例: -``` +```sh [TEST PROF INFO] Profile results to JSON: tmp/test_prof/test-prof.result.json ``` -## Factory Flamegraph +### 出力を減らす + +FactoryProf を実行すると、数回しか使われていないファクトリの行が出力に大量に含まれることがあります。 +これを避けて最も重要な統計に集中するために、しきい値を指定できます。すると、合計回数がしきい値を超えるファクトリだけが表示されます。 + +しきい値のオプションを使うには、環境変数 `FPROF_THRESHOLD` に `N` を設定します (`N` はしきい値の数です)。 + +```sh +FPROF=1 FPROF_THRESHOLD=30 rspec + +# または +FPROF=1 FPROF_THRESHOLD=30 bundle exec rake test +``` + +あるいは、`FactoryProf` の設定でしきい値のパラメータを指定することもできます。 + +```ruby +TestProf::FactoryProf.configure do |config| + config.threshold = 30 +end +``` + +### 長いファクトリ名を切り詰める + +ファクトリ名が長いコードベースで FactoryProf を実行すると、表のレイアウトが崩れることがあります。これを避けるために、FactoryProf に名前を切り詰めさせることができます。 + +切り詰めを使うには、環境変数 `FPROF_TRUNCATE_NAMES` に `1` を設定します。 + +```sh +FPROF=1 FPROF_TRUNCATE_NAMES=1 rspec + +# または +FPROF=1 FPROF_TRUNCATE_NAMES=1 bundle exec rake test +``` + +あるいは、`FactoryProf` の設定で truncate_names パラメータを指定することもできます。 + +```ruby +TestProf::FactoryProf.configure do |config| + config.truncate_names = true +end +``` + +## ファクトリのフレームグラフ -The most useful feature of FactoryProf is the _FactoryFlame_ report. That's the special interpretation of Brendan Gregg's [flame graphs](http://www.brendangregg.com/flamegraphs.html) which allows you to identify _factory cascades_. +FactoryProf の最も便利な機能が _FactoryFlame_ レポートです。これは Brendan Gregg の[フレームグラフ](http://www.brendangregg.com/flamegraphs.html)を独自に解釈したもので、_ファクトリカスケード_ を特定できます。 -To generate FactoryFlame report set `FPROF` environment variable to `flamegraph`: +FactoryFlame レポートを生成するには、環境変数 `FPROF` に `flamegraph` を設定します。 ```sh FPROF=flamegraph rspec -# or +# または FPROF=flamegraph bundle exec rake test ``` -That's how a report looks like: +レポートは次のような見た目になります。 -![](/assets/factory-flame.gif) +TagProf UI -How to read this? +これはどう読めばよいのでしょうか? -Every column represents a _factory stack_ or _cascade_, that is a sequence of recursive `#create` method calls. Consider an example: +それぞれの列は _ファクトリスタック_ または _カスケード_、つまり `#create` メソッドの再帰的な呼び出しの連なりを表します。次の例を考えてみましょう。 ```ruby factory :comment do @@ -109,18 +214,18 @@ factory :question do author end -create(:comment) #=> creates 5 records +create(:comment) #=> 5 件のレコードを作成する -# And the corresponding stack is: +# 対応するスタックは次のとおり: # [:comment, :answer, :question, :author, :author, :author] ``` -The wider column the more often this stack appears. +列の幅が広いほど、そのスタックが頻繁に現れていることを意味します。 -The `root` cell shows the total number of `create` calls. +`root` のセルには、`create` の呼び出しの合計回数が表示されます。 -## Acknowledgments +## 謝辞 -- Thanks to [Martin Spier](https://github.com/spiermar) for [d3-flame-graph](https://github.com/spiermar/d3-flame-graph) +- [d3-flame-graph](https://github.com/spiermar/d3-flame-graph) を作成した [Martin Spier](https://github.com/spiermar) に感謝します -- Thanks to [Sam Saffron](https://github.com/SamSaffron) for his [flame graphs implementation](https://github.com/SamSaffron/flamegraph). +- [フレームグラフの実装](https://github.com/SamSaffron/flamegraph)を作成した [Sam Saffron](https://github.com/SamSaffron) に感謝します。 diff --git a/docs/ja/guide/profilers/memory_prof.md b/docs/ja/guide/profilers/memory_prof.md index f0bd43d..e0d7a8a 100755 --- a/docs/ja/guide/profilers/memory_prof.md +++ b/docs/ja/guide/profilers/memory_prof.md @@ -1,8 +1,8 @@ # MemoryProf -MemoryProf tracks memory usage during your test suite run, and can help to detect test examples and groups that cause memory spikes. Memory profiling supports two metrics: RSS and allocations. +MemoryProf は、テストスイートの実行中のメモリ使用量を追跡し、メモリの急増を引き起こす example や group を見つけるのに役立ちます。メモリのプロファイリングは、RSS、アロケーション、GC 時間というメトリクスをサポートしています。 -Example output: +出力例: ```sh [TEST PROF INFO] MemoryProf results @@ -24,62 +24,66 @@ change Votes count (./spec/shared_examples/controllers/voted_examples.rb:23) – fails (./spec/shared_examples/controllers/invalid_examples.rb:3) – +32KB (5.00%) ``` -The examples block shows the amount of memory used by each example, and the groups block displays the memory allocated by other code defined in the groups. For example, RSpec groups may include heavy `before(:all)` (or `before_all`) setup blocks, so it is helpful to see which groups use the most amount of memory outside of their examples. +この出力は、各 example とトップレベルの example group (通常はテストファイル) が使用したメモリの量を示しています。 -## Instructions +## 使い方 -To activate MemoryProf with: +MemoryProf を有効にする方法は次のとおりです。 ### RSpec -Use `TEST_MEM_PROF` environment variable to set which metric to use: +環境変数 `TEST_MEM_PROF` で、使用するメトリクスを指定します。 ```sh TEST_MEM_PROF='rss' rspec ... TEST_MEM_PROF='alloc' rake rspec ... +TEST_MEM_PROF='gc' rake rspec ... ``` ### Minitest -Use `TEST_MEM_PROF` environment variable to set which metric to use: +Minitest 6 以降では、まずテストヘルパーに `Minitest.load :test_prof` を追加して、TestProf プラグインを有効にする必要があります。 + +環境変数 `TEST_MEM_PROF` で、使用するメトリクスを指定します。 ```sh TEST_MEM_PROF='rss' rake test -TEST_MEM_PROF='alloc' rspec ... +TEST_MEM_PROF='alloc' rake test +TEST_MEM_PROF='gc' rake test ``` -or use CLI options as well: +CLI オプションを使うこともできます。 ```sh -# Run a specific file using CLI option +# CLI オプションを使って特定のファイルを実行する ruby test/my_super_test.rb --mem-prof=rss -# Show the list of possible options: +# 使用できるオプションの一覧を表示する ruby test/my_super_test.rb --help ``` -## Configuration +## 設定 -By default, MemoryProf tracks the top 5 examples and groups that use the largest amount of memory. -You can set how many examples/groups to display with the option: +デフォルトでは、MemoryProf はメモリ使用量の多い上位 5 件の example と group を追跡します。 +表示する example や group の件数は、次のオプションで指定できます。 ```sh TEST_MEM_PROF='rss' TEST_MEM_PROF_COUNT=10 rspec ... ``` -or with CLI options for Minitest: +Minitest の場合は CLI オプションで指定します。 ```sh -# Run a specific file using CLI option +# CLI オプションを使って特定のファイルを実行する ruby test/my_super_test.rb --mem-prof=rs --mem-prof-top-count=10 ``` -## Supported Ruby Engines & OS +## サポートされる Ruby エンジンと OS -Currently the allocation mode is not supported for JRuby. +現在、アロケーションモードは JRuby ではサポートされていません。 -Since RSS depends on the OS, MemoryProf uses different tools to retrieve it: +RSS は OS に依存するため、MemoryProf は RSS の取得に OS ごとに異なる手段を使用します。 -* Linux – `/proc/$pid/statm` file, -* macOS, Solaris, BSD – `ps`, -* Windows – `Get-Process`, requires PowerShell to be installed. +* Linux – `/proc/$pid/statm` ファイル +* macOS, Solaris, BSD – `ps` +* Windows – `Get-Process` (PowerShell がインストールされている必要があります) diff --git a/docs/ja/guide/profilers/rspec_dissect.md b/docs/ja/guide/profilers/rspec_dissect.md index d09d7b2..0a9f861 100755 --- a/docs/ja/guide/profilers/rspec_dissect.md +++ b/docs/ja/guide/profilers/rspec_dissect.md @@ -1,82 +1,58 @@ # RSpecDissect -Do you know how much time you spend in `before` hooks? Or in memoization helpers such as `let`? Usually, the most of the whole test suite time. +`before` フックにどれだけの時間を費やしているかご存知ですか? あるいは、`let` のようなメモ化ヘルパーではどうでしょうか? たいていの場合、テストスイート全体の時間の大半を占めています。 -_RSpecDissect_ provides this kind of information and also shows you the worst example groups. The main purpose of RSpecDissect is to identify these slow groups and refactor them using [`before_all`](../recipes/before_all.md) or [`let_it_be`](../recipes/let_it_be.md) recipes. +_RSpecDissect_ はこういった情報を提供し、さらに **セットアップ時間** が最も長い example group を表示します。RSpecDissect の主な目的は、こうした遅いグループを特定し、[`before_all`](../recipes/before_all.md) や [`let_it_be`](../recipes/let_it_be.md) といったレシピを使ってリファクタリングすることです。 -Example output: +出力例: ```sh -[TEST PROF INFO] RSpecDissect enabled +[TEST PROF INFO] RSpecDissect report Total time: 25:14.870 -Total `before(:each)` time: 14:36.482 -Total `let` time: 19:20.259 - -Top 5 slowest suites (by `before(:each)` time): - -Webhooks::DispatchTransition (./spec/services/webhooks/dispatch_transition_spec.rb:3) – 00:29.895 of 00:33.706 (327) -FunnelsController (./spec/controllers/funnels_controller_spec.rb:3) – 00:22.117 of 00:43.649 (133) -ApplicantsController (./spec/controllers/applicants_controller_spec.rb:3) – 00:21.220 of 00:41.407 (222) -BookedSlotsController (./spec/controllers/booked_slots_controller_spec.rb:3) – 00:15.729 of 00:27.893 (50) -Analytics::Wor...rsion::Summary (./spec/services/analytics/workflow_conversion/summary_spec.rb:3) – 00:15.383 of 00:15.914 (12) - - -Top 5 slowest suites (by `let` time): - -FunnelsController (./spec/controllers/funnels_controller_spec.rb:3) – 00:38.532 of 00:43.649 (133) - ↳ user – 3 - ↳ funnel – 2 -ApplicantsController (./spec/controllers/applicants_controller_spec.rb:3) – 00:33.252 of 00:41.407 (222) - ↳ user – 10 - ↳ funnel – 5 - ↳ applicant – 2 -Webhooks::DispatchTransition (./spec/services/webhooks/dispatch_transition_spec.rb:3) – 00:30.320 of 00:33.706 (327) - ↳ user – 30 -BookedSlotsController (./spec/controllers/booked_slots_controller_spec.rb:3) – 00:25.710 of 00:27.893 e(50) - ↳ user – 21 - ↳ stage – 14 -AvailableSlotsController (./spec/controllers/available_slots_controller_spec.rb:3) – 00:18.481 of 00:23.366 (85) - ↳ user – 15 - ↳ stage – 10 +Total setup time: 14:36.482 + +Top 5 slowest suites setup time: + +Webhooks::DispatchTransition (./spec/services/webhooks/dispatch_transition_spec.rb:3) – 00:29.895 of 00:33.706 / 327 (before: 00:25.346, before let: 00:19.389, lazy let: 00:04.543) + ↳ user – 00:09.323 (327) + ↳ funnel – 00:06.231 (122) + ↳ account – 00:04.360 (91) + +FunnelsController (./spec/controllers/funnels_controller_spec.rb:3) – 00:22.117 of 00:43.649 / 133 (before: 00:22.117, before let: 00:18.695, lazy let: 00:00.000) + ↳ user – 00:09.323 (327) + ↳ funnel – 00:06.231 (122) +... ``` -As you can see, the `let` profiler also tracks the provides the information on how many times each `let` declarations has been used within a group (shows top-3 by default). +**セットアップ時間** には、`before(:each)` フックと遅延評価される `let` の評価に費やされた時間が含まれます (`subject` は除きます。`subject` はテスト対象のアクションを定義するために使われることが多く、セットアップフェーズの一部とみなすべきではないためです)。 + +ご覧のとおり、このプロファイラは評価に最も時間のかかっている `let` についての情報も提供します。 -## Instructions +## 使い方 -RSpecDissect can only be used with RSpec (which is clear from the name). +RSpecDissect は RSpec でのみ使用できます (名前からも明らかですね)。 -To activate RSpecDissect use `RD_PROF` environment variable: +RSpecDissect を有効にするには、環境変数 `RD_PROF` を使用します: ```sh RD_PROF=1 rspec ... ``` -You can also specify the number of top slow groups through `RD_PROF_TOP` variable: +`RD_PROF_TOP` 変数で、表示する遅いグループの上位件数を指定することもできます: ```sh RD_PROF=1 RD_PROF_TOP=10 rspec ... ``` -You can also track only `let` or `before` usage by specifying `RD_PROF=let` and `RD_PROF=before` respectively. - -For `let` profiler you can also specify the number of top `let` declarations to print through `RD_PROF_LET_TOP=10` env var. - -To disable `let` stats add: - -```ruby -TestProf::RSpecDissect.configure do |config| - config.let_stats_enabled = false -end -``` +また、環境変数 `RD_PROF_LET_TOP=10` で、表示する `let` 宣言の上位件数を指定できます。 -## Using with RSpecStamp +## RSpecStamp と組み合わせて使う -RSpecDissect can be used with [RSpec Stamp](../recipes/rspec_stamp.md) to automatically mark _slow_ examples with custom tags. For example: +RSpecDissect は [RSpec Stamp](../recipes/rspec_stamp.md) と組み合わせて、 _遅い_ example に自動的にカスタムタグを付けることができます。例: ```sh RD_PROF=1 RD_PROF_STAMP="slow" rspec ... ``` -After running the command above the slowest example groups would be marked with the `:slow` tag. +上記のコマンドを実行すると、最も遅い example group に `:slow` タグが付きます。 diff --git a/docs/ja/guide/profilers/ruby_prof.md b/docs/ja/guide/profilers/ruby_prof.md index 013f6b7..8b6f7ef 100755 --- a/docs/ja/guide/profilers/ruby_prof.md +++ b/docs/ja/guide/profilers/ruby_prof.md @@ -1,2 +1,2 @@ -

Please follow this link.

+

こちらのリンクをご覧ください。

diff --git a/docs/ja/guide/profilers/ruby_profilers.md b/docs/ja/guide/profilers/ruby_profilers.md index d52bd6c..0f7446a 100755 --- a/docs/ja/guide/profilers/ruby_profilers.md +++ b/docs/ja/guide/profilers/ruby_profilers.md @@ -1,9 +1,9 @@ -# Using with Ruby profilers +# Ruby プロファイラと組み合わせて使う -Test Prof allows you to use general Ruby profilers to profile test suites without needing to write any profiling code yourself. -Just install the profiler library and run your tests! +TestProf を使うと、プロファイリング用のコードを自分で書かなくても、一般的な Ruby プロファイラでテストスイートをプロファイリングできます。 +プロファイラのライブラリをインストールして、テストを実行するだけです! -Supported profilers: +サポートされているプロファイラ: - [StackProf](#stackprof) - [Vernier](#vernier) @@ -11,9 +11,9 @@ Supported profilers: ## StackProf -[StackProf][] is a sampling call-stack profiler for Ruby. +[StackProf][] は Ruby 用のサンプリング方式のコールスタックプロファイラです。 -Make sure you have `stackprof` in your dependencies: +依存関係に `stackprof` が含まれていることを確認してください: ```ruby # Gemfile @@ -22,20 +22,20 @@ group :development, :test do end ``` -### Profiling the whole test suite with StackProf +### StackProf でテストスイート全体をプロファイリングする -**NOTE:** It's recommended to use [test sampling](../recipes/tests_sampling.md) to generate smaller profiling reports. +**注意:** プロファイリングのレポートを小さくするために、[テストのサンプリング](../recipes/tests_sampling.md)を使用することをお勧めします。 -You can activate StackProf profiling by setting the `TEST_STACK_PROF` env variable: +環境変数 `TEST_STACK_PROF` を設定すると、StackProf によるプロファイリングを有効にできます: ```sh TEST_STACK_PROF=1 bundle exec rake test -# or for RSpec +# RSpec の場合 TEST_STACK_PROF=1 bundle exec rspec ... ``` -At the end of the test run, you will see the message from Test Prof including paths to generated reports (raw StackProf format and JSON): +テストの実行が終わると、生成されたレポート (StackProf の raw 形式と JSON) のパスを含む TestProf からのメッセージが表示されます: ```sh ... @@ -44,12 +44,12 @@ At the end of the test run, you will see the message from Test Prof including pa [TEST PROF INFO] StackProf JSON report generated: tmp/test_prof/stack-prof-report-wall-raw-total.json ``` -We recommend uploading JSON reports to [Speedscope][] and analyze flamegraphs. Otherwise, feel free to use the `stackprof` CLI -to manipulate the raw report. +JSON レポートを [Speedscope][] にアップロードして、フレームグラフを分析することをお勧めします。もちろん、`stackprof` の CLI +を使って raw レポートを扱っても構いません。 -### Profiling individual examples with StackProf +### StackProf で個々の example をプロファイリングする -Test Prof provides a built-in shared context for RSpec to profile examples individually: +TestProf は、example を個別にプロファイリングするための RSpec 用の組み込み shared context を提供しています: ```ruby it "is doing heavy stuff", :sprof do @@ -57,14 +57,14 @@ it "is doing heavy stuff", :sprof do end ``` -**NOTE:** per-example profiling doesn't work when the global (per-suite) profiling is activated. +**注意:** グローバルな (スイート単位の) プロファイリングが有効になっている場合、example 単位のプロファイリングは動作しません。 -### Profiling application boot with StackProf +### StackProf でアプリケーションの起動をプロファイリングする -The application boot time could also makes testing slower. Try to profile your boot process with StackProf using the following command: +アプリケーションの起動時間もテストを遅くする要因になりえます。次のコマンドを使って、起動処理を StackProf でプロファイリングしてみてください: ```sh -# pick some random spec (1 is enough) +# 適当な spec を選びます (1 つで十分です) $ TEST_STACK_PROF=boot bundle exec rspec ./spec/some_spec.rb ... @@ -72,25 +72,25 @@ $ TEST_STACK_PROF=boot bundle exec rspec ./spec/some_spec.rb [TEST PROF INFO] StackProf JSON report generated: tmp/test_prof/stack-prof-report-wall-raw-boot.json ``` -### StackProf configuration +### StackProf の設定 -You can change StackProf mode (which is `wall` by default) through `TEST_STACK_PROF_MODE` env variable. +StackProf のモード (デフォルトは `wall`) は、環境変数 `TEST_STACK_PROF_MODE` で変更できます。 -You can also change StackProf interval through `TEST_STACK_PROF_INTERVAL` env variable. -For modes `wall` and `cpu`, `TEST_STACK_PROF_INTERVAL` represents microseconds and will default to 1000 as per `stackprof`. -For mode `object`, `TEST_STACK_PROF_INTERVAL` represents allocations and will default to 1 as per `stackprof`. +StackProf のインターバルも、環境変数 `TEST_STACK_PROF_INTERVAL` で変更できます。 +`wall` モードと `cpu` モードでは、`TEST_STACK_PROF_INTERVAL` はマイクロ秒を表し、デフォルトは `stackprof` と同じ 1000 です。 +`object` モードでは、`TEST_STACK_PROF_INTERVAL` はアロケーション数を表し、デフォルトは `stackprof` と同じ 1 です。 -You can disable garbage collection frames by setting `TEST_STACK_PROF_IGNORE_GC` env variable. -Garbage collection time will still be present in the profile but not explicitly marked with -its own frame. +環境変数 `TEST_STACK_PROF_IGNORE_GC` を設定すると、ガベージコレクションのフレームを無効にできます。 +ガベージコレクションの時間はプロファイルに含まれたままですが、専用のフレームとして +明示されなくなります。 -See [stack_prof.rb](https://github.com/test-prof/test-prof/tree/master/lib/test_prof/stack_prof.rb) for all available configuration options and their usage. +利用可能なすべての設定オプションとその使い方については、[stack_prof.rb](https://github.com/test-prof/test-prof/tree/master/lib/test_prof/stack_prof.rb) を参照してください。 ## Vernier -[Vernier][] is next generation sampling profiler for Ruby. Give it a try and see if it can help in identifying test peformance bottlenecks! +[Vernier][] は Ruby 用の次世代のサンプリングプロファイラです。ぜひ試してみて、テストの性能のボトルネックを特定するのに役立つか確かめてください! -Make sure you have `vernier` in your dependencies: +依存関係に `vernier` が含まれていることを確認してください: ```ruby # Gemfile @@ -99,20 +99,20 @@ group :development, :test do end ``` -### Profiling the whole test suite with Vernier +### Vernier でテストスイート全体をプロファイリングする -**NOTE:** It's recommended to use [test sampling](../recipes/tests_sampling.md) to generate smaller profiling reports. +**注意:** プロファイリングのレポートを小さくするために、[テストのサンプリング](../recipes/tests_sampling.md)を使用することをお勧めします。 -You can activate Verner profiling by setting the `TEST_VERNIER` env variable: +環境変数 `TEST_VERNIER` を設定すると、Vernier によるプロファイリングを有効にできます: ```sh TEST_VERNIER=1 bundle exec rake test -# or for RSpec +# RSpec の場合 TEST_VERNIER=1 bundle exec rspec ... ``` -At the end of the test run, you will see the message from Test Prof including the path to the generated report: +テストの実行が終わると、生成されたレポートのパスを含む TestProf からのメッセージが表示されます: ```sh ... @@ -120,11 +120,11 @@ At the end of the test run, you will see the message from Test Prof including th [TEST PROF INFO] Vernier report generated: tmp/test_prof/vernier-report-wall-raw-total.json ``` -Use the [profile-viewer](https://github.com/tenderlove/profiler/tree/ruby) gem or upload your profiles to [profiler.firefox.com](https://profiler.firefox.com). +[profile-viewer](https://github.com/tenderlove/profiler/tree/ruby) gem を使うか、プロファイルを [vernier.prof](https://vernier.prof) にアップロードしてください。あるいは、profile-viewer のフォーク元である [profiler.firefox.com](https://profiler.firefox.com) を使うこともできます。 -### Profiling individual examples with Vernier +### Vernier で個々の example をプロファイリングする -Test Prof provides a built-in shared context for RSpec to profile examples individually: +TestProf は、example を個別にプロファイリングするための RSpec 用の組み込み shared context を提供しています: ```ruby it "is doing heavy stuff", :vernier do @@ -132,22 +132,41 @@ it "is doing heavy stuff", :vernier do end ``` -**NOTE:** per-example profiling doesn't work when the global (per-suite) profiling is activated. +**注意:** グローバルな (スイート単位の) プロファイリングが有効になっている場合、example 単位のプロファイリングは動作しません。 -### Profiling application boot with Vernier +### Vernier でアプリケーションの起動をプロファイリングする -You can also profile your application boot process: +アプリケーションの起動処理をプロファイリングすることもできます: ```sh -# pick some random spec (1 is enough) +# 適当な spec を選びます (1 つで十分です) TEST_VERNIER=boot bundle exec rspec ./spec/some_spec.rb ``` +### Active Support Notifications からマーカーを追加する + +Active Support Notifications のイベントマーカーを追加すると、生成されるレポートからより多くの知見を得られます: + +```sh +TEST_VERNIER=1 TEST_VERNIER_HOOKS=rails bundle exec rake test + +# RSpec の場合 +TEST_VERNIER=1 TEST_VERNIER_HOOKS=rails bundle exec rspec ... +``` + +あるいは、`Vernier` の設定で hooks パラメータを指定することもできます: + +```ruby +TestProf::Vernier.configure do |config| + config.hooks = :rails +end +``` + ## RubyProf -Easily integrate the power of [ruby-prof](https://github.com/ruby-prof/ruby-prof) into your test suite. +[ruby-prof](https://github.com/ruby-prof/ruby-prof) の力を、テストスイートに簡単に組み込めます。 -Make sure `ruby-prof` is installed: +`ruby-prof` がインストールされていることを確認してください: ```ruby # Gemfile @@ -156,28 +175,44 @@ group :development, :test do end ``` -### Profiling the whole test suite with RubyProf +### RubyProf でテストスイート全体をプロファイリングする -**NOTE:** It's highly recommended to use [test sampling](../recipes/tests_sampling.md) to generate smaller profiling reports and avoid slow test runs (RubyProf has a signifact overhead). +**注意:** プロファイリングのレポートを小さくし、テストの実行が遅くなるのを避けるために、[テストのサンプリング](../recipes/tests_sampling.md)を使用することを強くお勧めします (RubyProf にはかなりのオーバーヘッドがあります)。 -You can activate the global profiling using the environment variable `TEST_RUBY_PROF`: +環境変数 `TEST_RUBY_PROF` を使うと、グローバルなプロファイリングを有効にできます: ```sh TEST_RUBY_PROF=1 bundle exec rake test -# or for RSpec +# RSpec の場合 TEST_RUBY_PROF=1 bundle exec rspec ... ``` -At the end of the test run, you will see the message from Test Prof including paths to generated reports: +テストの実行が終わると、生成されたレポートのパスを含む TestProf からのメッセージが表示されます: ```sh [TEST PROF INFO] RubyProf report generated: tmp/test_prof/ruby-prof-report-flat-wall-total.txt ``` -### Profiling individual examples with RubyProf +#### テストスイートの起動を除外する + +**注意:** RSpec のみ対応しています。 + +アプリケーションの起動とテストの読み込みを RubyProf のレポートから除外し、実行されるテストだけを分析できると便利なことがあります (そうすれば、`Kernel#require` が最も遅いメソッドの上位に入ることもありません)。 + +そのためには、環境変数 `TEST_RUBY_PROF_BOOT=false` (または "0"、"f") を指定します: + +```sh +$ TEST_RUBY_PROF=1 TEST_RUBY_PROF_BOOT=0 bundle exec rspec ... + +[TEST PROF] RubyProf enabled for examples + +... +``` + +### RubyProf で個々の example をプロファイリングする -TestProf provides a built-in shared context for RSpec to profile examples individually: +TestProf は、example を個別にプロファイリングするための RSpec 用の組み込み shared context を提供しています: ```ruby it "is doing heavy stuff", :rprof do @@ -185,19 +220,19 @@ it "is doing heavy stuff", :rprof do end ``` -**NOTE:** per-example profiling doesn't work when the global profiling is activated. +**注意:** グローバルなプロファイリングが有効になっている場合、example 単位のプロファイリングは動作しません。 -### RubyProf configuration +### RubyProf の設定 -The most useful configuration option is `printer` – it allows you to specify a RubyProf [printer](https://github.com/ruby-prof/ruby-prof#printers). +最も便利な設定オプションは `printer` です。これにより、RubyProf の [printer](https://github.com/ruby-prof/ruby-prof#printers) を指定できます。 -You can specify a printer through environment variable `TEST_RUBY_PROF`: +printer は環境変数 `TEST_RUBY_PROF` で指定できます: ```sh TEST_RUBY_PROF=call_stack bundle exec rake test ``` -Or in your code: +あるいは、コードの中で指定します: ```ruby TestProf::RubyProf.configure do |config| @@ -205,22 +240,22 @@ TestProf::RubyProf.configure do |config| end ``` -By default, we use `FlatPrinter`. +デフォルトでは `FlatPrinter` を使用します。 -**NOTE:** to specify the printer for per-example profiles use `TEST_RUBY_PROF_PRINTER` env variable ('cause using `TEST_RUBY_PROF` activates the global profiling). +**注意:** example 単位のプロファイルの printer を指定するには、環境変数 `TEST_RUBY_PROF_PRINTER` を使用してください (`TEST_RUBY_PROF` を使うとグローバルなプロファイリングが有効になってしまうためです)。 -Also, you can specify RubyProf mode (`wall`, `cpu`, etc) through `TEST_RUBY_PROF_MODE` env variable. +また、RubyProf のモード (`wall`、`cpu` など) は環境変数 `TEST_RUBY_PROF_MODE` で指定できます。 -See [ruby_prof.rb](https://github.com/test-prof/test-prof/tree/master/lib/test_prof/ruby_prof.rb) for all available configuration options and their usage. +利用可能なすべての設定オプションとその使い方については、[ruby_prof.rb](https://github.com/test-prof/test-prof/tree/master/lib/test_prof/ruby_prof.rb) を参照してください。 -It's useful to exclude some methods from the profile to focus only on the application code. +アプリケーションのコードだけに集中するために、一部のメソッドをプロファイルから除外すると便利です。 -TestProf uses RubyProf [`exclude_common_methods!`](https://github.com/ruby-prof/ruby-prof/blob/e087b7d7ca11eecf1717d95a5c5fea1e36ea3136/lib/ruby-prof/profile/exclude_common_methods.rb) by default (disable it with `config.exclude_common_methods = false`). +TestProf はデフォルトで RubyProf の [`exclude_common_methods!`](https://github.com/ruby-prof/ruby-prof/blob/e087b7d7ca11eecf1717d95a5c5fea1e36ea3136/lib/ruby-prof/profile/exclude_common_methods.rb) を使用します (`config.exclude_common_methods = false` で無効にできます)。 -We exclude some other common methods and RSpec specific internal methods by default. -To disable TestProf-defined exclusions set `config.test_prof_exclusions_enabled = false`. +そのほかの一般的なメソッドや RSpec 固有の内部メソッドも、デフォルトで除外しています。 +TestProf が定義している除外設定を無効にするには、`config.test_prof_exclusions_enabled = false` を設定してください。 -You can specify custom exclusions through `config.custom_exclusions`, e.g.: +`config.custom_exclusions` で独自の除外設定を指定できます。例: ```ruby TestProf::RubyProf.configure do |config| diff --git a/docs/ja/guide/profilers/stack_prof.md b/docs/ja/guide/profilers/stack_prof.md index 013f6b7..8b6f7ef 100755 --- a/docs/ja/guide/profilers/stack_prof.md +++ b/docs/ja/guide/profilers/stack_prof.md @@ -1,2 +1,2 @@ -

Please follow this link.

+

こちらのリンクをご覧ください。

diff --git a/docs/ja/guide/profilers/tag_prof.md b/docs/ja/guide/profilers/tag_prof.md index d350632..e1b6bdb 100755 --- a/docs/ja/guide/profilers/tag_prof.md +++ b/docs/ja/guide/profilers/tag_prof.md @@ -1,10 +1,10 @@ # TagProf -TagProf is a simple profiler which collects examples statistics grouped by a provided tag value. +TagProf は、指定されたタグの値ごとに example の統計情報をまとめて収集するシンプルなプロファイラです。 -That's pretty useful in conjunction with `rspec-rails` built-in feature – `infer_spec_type_from_file_location!` – which automatically adds `type` to examples metadata. +これは、`rspec-rails` の組み込み機能である `infer_spec_type_from_file_location!` (example のメタデータに自動的に `type` を追加する機能) と組み合わせるととても便利です。 -Example output: +出力例: ```sh [TEST PROF INFO] TagProf report for type @@ -16,50 +16,52 @@ Example output: model 00:01.127 40 32.26 12.82 00:00.028 ``` -It shows both the total number of examples in each group and the total time spent (as long as percentages and average values). +各グループの example の総数と、費やされた合計時間の両方が表示されます (割合と平均値も表示されます)。 -You can also generate an interactive HTML report: +インタラクティブな HTML レポートを生成することもできます: ```sh TAG_PROF=type TAG_PROF_FORMAT=html bundle exec rspec ``` -That's how a report looks like: +レポートは次のように表示されます: -![TagProf UI](/assets/tag-prof.gif) +TagProf UI -## Instructions +## 使い方 -TagProf can be used with both RSpec and Minitest (limited support, see below). +TagProf は RSpec と Minitest の両方で使用できます (Minitest は限定的なサポートです。下記を参照してください)。 -To activate TagProf use `TAG_PROF` environment variable: +TagProf を有効にするには、環境変数 `TAG_PROF` を使用します: -With Rspec: +RSpec の場合: ```sh -# Group by type +# type でグループ化する TAG_PROF=type rspec ``` -With Minitest: +Minitest の場合\*: ```sh -# using pure ruby +# 素の ruby を使う場合 TAG_PROF=type ruby -# using Rails built-in task +# Rails の組み込みタスクを使う場合 TAG_PROF=type bin/rails test ``` -NB: if another value than "type" is used for TAG_PROF environment variable it will be ignored silently in both Minitest and RSpec. +注: 環境変数 TAG_PROF に "type" 以外の値を指定した場合、Minitest と RSpec のどちらでも、何も表示されずに無視されます。 -### Usage specificity with Minitest +\* Minitest 6 以降では、まずテストヘルパーに `Minitest.load :test_prof` を追加して、TestProf プラグインを有効にする必要があります。 -Minitest does not support the usage of tags by default. TagProf therefore groups statistics by direct subdirectories of the root test directory. It assumes root test directory is named either `spec` or `test`. +### Minitest での使い方の違い -When no root test directory can be found the test statistics will not be grouped with other tests. They will be displayed per test with a significant warning message in the report. +Minitest はデフォルトではタグの使用をサポートしていません。そのため TagProf は、テストのルートディレクトリ直下のサブディレクトリごとに統計情報をグループ化します。テストのルートディレクトリの名前は `spec` か `test` のいずれかであることを前提としています。 -Example: +テストのルートディレクトリが見つからない場合、そのテストの統計情報は他のテストとグループ化されません。その場合、レポートに目立つ警告メッセージが出たうえで、テストごとに表示されます。 + +例: ```sh [TEST PROF INFO] TagProf report for type @@ -71,15 +73,15 @@ __unknown__ 00:04.808 00:01.402 42 33.87 54.70 00:00.1 model 00:01.127 00:00.446 40 32.26 12.82 00:00.028 ``` -## Profiling events +## イベントのプロファイリング -You can combine TagProf with [EventProf](./event_prof.md) to track not only the total time spent but also the time spent for the specified activities (through events): +TagProf を [EventProf](./event_prof.md) と組み合わせると、費やされた合計時間だけでなく、(イベントを通じて) 指定したアクティビティに費やされた時間も追跡できます: ``` TAG_PROF=type TAG_PROF_EVENT=sql.active_record rspec ``` -Example output: +出力例: ```sh [TEST PROF INFO] TagProf report for type @@ -91,20 +93,20 @@ Example output: model 00:01.127 00:00.446 40 32.26 12.82 00:00.028 ``` -Multiple events are also supported (comma-separated). +複数のイベントにも対応しています (カンマ区切りで指定します)。 -## Pro-Tip: More Types +## 上級者向けのヒント: type を増やす -By default, RSpec only infers types for default Rails app entities (such as controllers, models, mailers, etc.). -Modern Rails applications typically contain other abstractions too (e.g. services, forms, presenters, etc.), but RSpec is not aware of them and doesn't add any metadata. +デフォルトでは、RSpec は Rails アプリケーションの標準的な構成要素 (コントローラ、モデル、メーラーなど) についてのみ type を推測します。 +最近の Rails アプリケーションには、たいていそれ以外の抽象化 (サービス、フォーム、プレゼンターなど) も含まれていますが、RSpec はそれらを認識せず、メタデータを追加しません。 -That's the quick workaround: +手軽な回避策は次のとおりです: ```ruby RSpec.configure do |config| # ... config.define_derived_metadata(file_path: %r{/spec/}) do |metadata| - # do not overwrite type if it's already set + # type がすでに設定されている場合は上書きしない next if metadata.key?(:type) match = metadata[:location].match(%r{/spec/([^/]+)/}) diff --git a/docs/ja/guide/profilers/tps_prof.md b/docs/ja/guide/profilers/tps_prof.md new file mode 100644 index 0000000..e3c9250 --- /dev/null +++ b/docs/ja/guide/profilers/tps_prof.md @@ -0,0 +1,139 @@ +# TPSProf + +@available_since version=1.6.0 + +TPSProf は、トップレベルの example group ごとに 1 秒あたりのテスト数 (TPS: tests-per-second) を計測し、最も遅いグループを特定するのに役立ちます。また、**strict モード** で実行すると、TPS がしきい値を下回るグループがあるときにビルドを失敗させることもできます。 + +出力例: + +```sh +[TEST PROF INFO] TPSProf enabled (top-10) + +[TEST PROF INFO] Total TPS (tests per second): 12.33 + +Top 10 slowest suites by TPS (tests per second): + +UsersController (./spec/controllers/users_controller_spec.rb:3) – 3.45 TPS (00:05.797 / 20, shared setup time: 00:01.203) +PostsController (./spec/controllers/posts_controller_spec.rb:3) – 5.12 TPS (00:03.906 / 20, shared setup time: 00:00.876) +CommentsController (./spec/controllers/comments_controller_spec.rb:3) – 7.89 TPS (00:01.900 / 15, shared setup time: 00:00.410) +``` + +出力には、各グループの TPS と合わせて、合計時間、example の数、共有セットアップ時間 (`before(:all)` フックなど、個々の example の外で費やされた時間) が表示されます。 + +_ペナルティ_ が最も大きいグループから順に表示されます。ペナルティは、目標 TPS (デフォルトは 30) と比べて無駄になった時間として計算されます。 _ペナルティ_ という考え方の狙いは、最適化したときにテストスイートの時間を最も節約できる example group を特定することです。つまり、ペナルティが最も大きいグループが TPS の最も低いグループであるとは限らず、グループ内の example の総数にも左右されます。より正確な結果を得るには、目標 TPS を調整してください。 + +## 使い方 + +TPSProf は現在 RSpec のみをサポートしています。 + +### profile モード (デフォルト) + +有効にするには、環境変数 `TPS_PROF` を使用します: + +```sh +# 最も遅いグループの上位 10 件を表示する (デフォルト) +TPS_PROF=1 rspec + +# 最も遅いグループの上位 N 件を表示する +TPS_PROF=20 rspec +``` + +### strict モード + +strict モードでは、しきい値に違反したグループを example 外のエラーとして報告し、ビルドを失敗させます: + +```sh +TPS_PROF=strict rspec +``` + +strict モードでは、違反を報告するためのしきい値を設定します: + +```sh +# example が 50 件を超えるグループを失敗させる +TPS_PROF=strict TPS_PROF_MAX_EXAMPLES=50 rspec + +# 30 秒を超えるグループを失敗させる +TPS_PROF=strict TPS_PROF_MAX_TIME=30 rspec + +# TPS が 5 未満のグループを失敗させる +TPS_PROF=strict TPS_PROF_MIN_TPS=5 rspec +``` + +複数のしきい値を組み合わせることもできます: + +```sh +TPS_PROF=strict TPS_PROF_MIN_TPS=5 TPS_PROF_MAX_TIME=30 rspec +``` + +## 設定 + +### 絞り込みのしきい値 + +グループは、以下の条件を **すべて** 満たす場合にのみレポートに含まれます: + +| 環境変数 | デフォルト | 説明 | +|---|---|---| +| `TPS_PROF_MIN_EXAMPLES` | 10 | グループ内の example の最小数 | +| `TPS_PROF_MIN_TIME` | 5 | グループの合計時間の最小値 (秒) | +| `TPS_PROF_TARGET_TPS` | 30 | TPS がこの値を下回るグループだけを報告する | + +### レポートのオプション + +| 環境変数 | デフォルト | 説明 | +|---|---|---| +| `TPS_PROF` | – | プロファイラを有効にする。数値を指定すると上位 N 件、`strict` を指定すると strict モードになる | +| `TPS_PROF_COUNT` | 10 | 表示するグループの数 (`TPS_PROF` の数値を上書きする) | +| `TPS_PROF_MODE` | – | モード (`profile` または `strict`) を明示的に指定する。`TPS_PROF=strict` を上書きする | + +### strict モードのしきい値 + +| 環境変数 | デフォルト | 説明 | +|---|---|---| +| `TPS_PROF_MAX_EXAMPLES` | – | example の数がこの値を超えるグループを報告する | +| `TPS_PROF_MAX_TIME` | – | 合計時間がこの値 (秒) を超えるグループを報告する | +| `TPS_PROF_MIN_TPS` | – | TPS がこの値を下回るグループを報告する | + +### コードによる設定 + +テストヘルパーの中で TPSProf を設定することもできます: + +```ruby +TestProf::TPSProf.configure do |config| + config.top_count = 15 + # プロファイリングのしきい値 + config.min_examples_count = 5 + config.min_group_time = 3 + config.min_target_tps = 20 + # strict モードの設定 + config.max_examples_count = 100 + config.max_group_time = 60 + config.min_tps = 5 +end +``` + +### カスタム strict ハンドラ + +カスタムの strict ハンドラを指定すると、独自の違反判定ロジックを実装できます。ハンドラは、`group`、`location`、`examples_count`、`total_time`、`tps`、`penalty` という属性を持つ `GroupInfo` オブジェクトを受け取ります。グループを違反として扱うには、例外を発生させてください。以下は、テストの種類ごとに異なる TPS のしきい値を使う設定例です: + +```ruby +TestProf::TPSProf.configure do |config| + config.mode = :strict + config.strict_handler = ->(group_info) { + if group_info.group.metadata[:type] == :system && group_info.tps < 5 + raise "Group #{group_info.location} is too slow: #{group_info.tps} TPS" + elsif group_info.tps < 20 + raise "Group #{group_info.location} is too slow: #{group_info.tps} TPS" + end + } +end +``` + +## グループと example を無視する + +`tps_prof: :ignore` メタデータを使うと、特定のグループを TPSProf の計測対象から除外できます: + +```ruby +RSpec.describe "SlowButOk", tps_prof: :ignore do + # ... +end +``` diff --git a/docs/ja/guide/recipes/active_record_shared_connection.md b/docs/ja/guide/recipes/active_record_shared_connection.md index f1e3cd2..616de08 100755 --- a/docs/ja/guide/recipes/active_record_shared_connection.md +++ b/docs/ja/guide/recipes/active_record_shared_connection.md @@ -1,28 +1,28 @@ # Active Record Shared Connection -> 💀 This functionality has been removed in v1.0. +> 💀 この機能は v1.0 で削除されました。 -**NOTE:** a similar functionality has been added to Rails since version 5.1 (see [PR](https://github.com/rails/rails/pull/28083)). You shouldn't use `ActiveRecordSharedConnection` with modern Rails, it could lead to unexpected behaviour (e.g., mutexes deadlocks). +**注意:** 同様の機能が、バージョン 5.1 以降の Rails に追加されています ([PR](https://github.com/rails/rails/pull/28083) を参照)。最近の Rails では `ActiveRecordSharedConnection` を使うべきではありません。予期しない動作 (たとえば mutex のデッドロック) を引き起こすおそれがあります。 -Active Record creates a connection per thread by default. +Active Record は、デフォルトではスレッドごとにコネクションを作成します。 -That doesn't allow us to use `transactional_tests` feature in system (with Capybara) tests (since Capybara runs a web server in a separate thread). +そのため、(Capybara を使う) システムテストでは `transactional_tests` 機能を使えません (Capybara は Web サーバーを別のスレッドで実行するためです)。 -A common approach is to use `database_cleaner` with a non-transactional strategy (`truncation` / `deletion`). But that _cleaning_ phase may affect tests run time (and usually does). +よくある方法は、`database_cleaner` をトランザクションを使わないストラテジー (`truncation` / `deletion`) で使うことです。しかし、この _クリーニング_ のフェーズはテストの実行時間に影響することがあります (そして、たいていは影響します)。 -Sharing the connection between threads would allows us to use transactional tests as always. +スレッド間でコネクションを共有すれば、いつもどおりトランザクショナルテストを使えるようになります。 -## Instructions +## 使い方 -In your `spec_helper.rb` (or `rails_helper.rb` if any): +`spec_helper.rb` (あれば `rails_helper.rb`) に以下を追加してください。 ```ruby require "test_prof/recipes/active_record_shared_connection" ``` -That automatically enables _shared connection_ mode. +これにより、_shared connection_ モードが自動的に有効になります。 -You can enable/disable it manually: +手動で有効・無効を切り替えることもできます。 ```ruby TestProf::ActiveRecordSharedConnection.enable! diff --git a/docs/ja/guide/recipes/any_fixture.md b/docs/ja/guide/recipes/any_fixture.md index a6c19ff..8672dfb 100755 --- a/docs/ja/guide/recipes/any_fixture.md +++ b/docs/ja/guide/recipes/any_fixture.md @@ -1,81 +1,78 @@ # AnyFixture -Fixtures are a great way to increase your test suite performance, but for a large project, they are very hard to maintain. +フィクスチャはテストスイートの性能を上げる優れた方法ですが、大規模なプロジェクトでは保守がとても難しくなります。 -We propose a more general approach to lazy-generate the _global_ state for your test suite – AnyFixture. +そこで私たちは、テストスイートの _グローバルな_ 状態を遅延生成する、より汎用的なアプローチである AnyFixture を提案します。 -With AnyFixture, you can use any block of code for data generation, and it will take care of cleaning it out at the end of the run. +AnyFixture では、任意のコードブロックをデータ生成に使うことができ、実行の最後にそのデータを片付ける処理も AnyFixture が引き受けます。 -Consider an example: +次の例を考えます。 ```ruby -# The best way to use AnyFixture is through RSpec shared contexts +# AnyFixture を使う一番良い方法は、RSpec の shared context を経由することです RSpec.shared_context "account", account: true do - # You should call AnyFixture outside of transaction to re-use the same - # data between examples + # example 間で同じデータを再利用するために、 + # AnyFixture はトランザクションの外で呼び出す必要があります before(:all) do - # The provided name ("account") should be unique. + # 指定する名前 ("account") は一意でなければなりません。 @account = TestProf::AnyFixture.register(:account) do - # Do anything here, AnyFixture keeps track of affected DB tables - # For example, you can use factories here + # ここでは何をしても構いません。AnyFixture は影響を受けた DB テーブルを追跡します + # たとえば、ここでファクトリを使うことができます FactoryBot.create(:account) - # or with Fabrication + # あるいは Fabrication を使う Fabricate(:account) - # or with plain old AR + # あるいは昔ながらの素の AR を使う Account.create!(name: "test") end end - # Use .register here to track the usage stats (see below) - let(:account) { TestProf::AnyFixture.register(:account) } - - # Or hard-reload object if there is chance of in-place modification - let(:account) { Account.find(TestProf::AnyFixture.register(:account).id) } + # フィクスチャのレコードを取得するには .cached を使います + let(:account) { TestProf::AnyFixture.cached(:account) } end -# You can enhance the existing database cleaning. Posts will be deleted before fixtures reset +# 既存のデータベースのクリーニングを拡張することもできます。Post はフィクスチャのリセット前に削除されます TestProf::AnyFixture.before_fixtures_reset do Post.delete_all end -# Or after reset +# あるいはリセットの後に TestProf::AnyFixture.after_fixtures_reset do Post.delete_all end -# Then in your tests +# そして、テストの中では -# Active this fixture using a tag +# タグを使ってこのフィクスチャを有効にします describe UsersController, :account do # ... end -# This test also uses the same account record, -# no double-creation +# このテストも同じ account レコードを使います。 +# 二重に作成されることはありません describe PostsController, :account do # ... end ``` -See real life [example](http://bit.ly/any-fixture). +実際の[使用例](http://bit.ly/any-fixture)もご覧ください。 -## Instructions +## 使い方 ### RSpec -In your `spec_helper.rb` (or `rails_helper.rb` if you have one): +`spec_helper.rb` (`rails_helper.rb` がある場合はそちら) に次の記述を追加してください。 ```ruby require "test_prof/recipes/rspec/any_fixture" ``` -Now you can use `TestProf::AnyFixture` in your tests. +これで、テストの中で `TestProf::AnyFixture` を使えるようになります。 ### Minitest -When using AnyFixture with Minitest, you should take care of cleaning the database after each test run by yourself. For example: +AnyFixture を Minitest で使う場合は、テスト実行後のデータベースのクリーニングを自分で行う必要があります。たとえば次のようにします。 ```ruby # test_helper.rb @@ -87,50 +84,51 @@ at_exit { TestProf::AnyFixture.clean } ## DSL -We provide an optional _syntactic sugar_ (through Refinement) to make it easier to define fixtures and use callbacks: +フィクスチャの定義やコールバックの利用を簡単にするために、(Refinement を通じて) 任意で使える _シンタックスシュガー_ を用意しています。 ```ruby require "test_prof/any_fixture/dsl" -# Enable DSL -using TestProf::AnyFixture::DSL +# RSpec で DSL を有効にする +RSpec.configure do |config| + config.include TestProf::AnyFixture::DSL +end -# and then you can use `fixture` method (which is just an alias for `TestProf::AnyFixture.register`) -before(:all) { fixture(:account) } +# Minitest +class MyBaseTestCase < Minitest::Test + include TestProf::AnyFixture::DSL +end -# You can also use it to fetch the record (instead of storing it in instance variable) +# これで `fixture` メソッド (`TestProf::AnyFixture.register` の単なるエイリアス) を使えます +before(:all) { fixture(:account) { create(:account) } } + +# (インスタンス変数に保存する代わりに) レコードの取得にも使えます let(:account) { fixture(:account) } -# You can just use `before_fixtures_reset` or `after_fixtures_reset` callbacks +# `before_fixtures_reset` や `after_fixtures_reset` コールバックもそのまま使えます before_fixtures_reset { Post.delete_all } after_fixtures_reset { Post.delete_all } ``` -## `ActiveRecord#refind` - -TestProf also provides an extension to _hard-reload_ ActiveRecord objects: +なお、`#fixture` メソッドは読み出し時に Active Record オブジェクトを _再検索_ します。つまり、次の 2 つの式は同じように動作します。 ```ruby -# instead of -let(:account) { Account.find(fixture(:account).id) } - -# load refinement -require "test_prof/ext/active_record_refind" +let(:account) { fixture(:account) } -using TestProf::Ext::ActiveRecordRefind +# 次と同様 -let(:account) { fixture(:account).refind } +let(:account) { Account.find(TestProf::AnyFixture.cached(:account).id) } ``` -## Temporary disable fixtures +## フィクスチャを一時的に無効にする -Some of your tests might rely on _clean database_. Thus running them along with AnyFixture-dependent tests, could produce failures. +テストの中には _クリーンなデータベース_ に依存するものがあるかもしれません。そうしたテストを AnyFixture に依存するテストと一緒に実行すると、失敗することがあります。 -You can disable (or delete) all created fixture while running a specified example or group using the `:with_clean_fixture` shared context: +`:with_clean_fixture` shared context を使うと、指定した example や example group の実行中、作成済みのフィクスチャをすべて無効にする (削除する) ことができます。 ```ruby context "global state", :with_clean_fixture do - # or include explicitly + # あるいは明示的に include する # include_context "any_fixture:clean" specify "table is empty or smth like this" do @@ -139,13 +137,18 @@ context "global state", :with_clean_fixture do end ``` -How does it work? It wraps the example group into a transaction (using [`before_all`](./before_all.md)) and calls `TestProf::AnyFixture.clean` before running the examples. +どのような仕組みでしょうか? これは example group を ([`before_all`](./before_all.md) を使って) トランザクションで包み、example の実行前に `TestProf::AnyFixture.clean` と `TestProf::AnyFixture.disable!` を呼び出し、コンテキストを抜けるときに `TestProf::AnyFixture.enable!` を呼び出します。`disable!` / `enable!` メソッドはキャッシュの状態を切り替えます。これにより、登録時に渡したブロックを、AnyFixture が存在しないかのように再利用できます。 + +```ruby +# AnyFixture が無効になっている場合、ここで新しい account を作成します +let(:account) { fixture(:account) { create(:account) } } +``` -Thus, this context is a little bit _heavy_. Try to avoid such situations and write specs independent of the global state. +フィクスチャのリセット (つまり、影響を受けたテーブルからのデータ削除) は _重い_ 処理になることがあります。そのような状況は避け、グローバルな状態に依存しない spec を書くようにしてください。 -## Usage report +## 使用状況のレポート -`AnyFixture` collects the usage information during the test run and could report it at the end: +`AnyFixture` はテストの実行中に使用状況の情報を収集し、最後にそれをレポートすることができます。 ```sh [TEST PROF INFO] AnyFixture usage stats: @@ -160,91 +163,91 @@ Total time saved: 00:00.019 Total time wasted: 00:00.000 ``` -The reporting is off by default, to enable the reporting set `TestProf::AnyFixture.config.reporting_enabled = true` (or you can invoke it manually through `TestProf::AnyFixture.report_stats`). +レポートはデフォルトではオフになっています。有効にするには `TestProf::AnyFixture.config.reporting_enabled = true` を設定してください (あるいは `TestProf::AnyFixture.report_stats` を通じて手動で呼び出すこともできます)。 -You can also enable reporting through the `ANYFIXTURE_REPORT=1` env variable. +環境変数 `ANYFIXTURE_REPORT=1` でレポートを有効にすることもできます。 -## Using auto-generated SQL dumps +## 自動生成された SQL ダンプを使う > @since v1.0, experimental -AnyFixture is designed to generate data once per a test suite run (and cleanup in the end). It still could be time-consuming (e.g., for system or performance tests); thus, we want to optimize further. +AnyFixture は、テストスイートの実行 1 回につき 1 度だけデータを生成する (そして最後にクリーンアップする) ように設計されています。それでも (システムテストやパフォーマンステストなどでは) 時間がかかることがあるため、さらに最適化したくなります。 -We provide another way of speeding up test data called `#register_dump`. It works similarly to `#register` for the first run: it accepts a block of code and tracks SQL queries made within it. Then, it generates a plain SQL dump representing the data creating or modified during the call and uses this dump to restore the database state for the subsequent test runs. +そこで、テストデータの準備を高速化するもう 1 つの方法として `#register_dump` を用意しています。初回の実行では `#register` と同じように動作します。つまり、コードブロックを受け取り、その中で発行された SQL クエリを追跡します。そして、その呼び出しの中で作成または変更されたデータを表す素の SQL ダンプを生成し、以降のテスト実行ではこのダンプを使ってデータベースの状態を復元します。 -Let's consider an example: +例を見てみましょう。 ```ruby RSpec.shared_context "account", account: true do - # You should call AnyFixture outside of transaction to re-use the same - # data between examples + # example 間で同じデータを再利用するために、 + # AnyFixture はトランザクションの外で呼び出す必要があります before(:all) do - # The block is called once per test run (similary to #register) + # このブロックはテスト実行 1 回につき 1 度だけ呼び出されます (#register と同様) TestProf::AnyFixture.register_dump("account") do - # Do anything here, AnyFixture keeps track of affected DB tables - # For example, you can use factories here + # ここでは何をしても構いません。AnyFixture は影響を受けた DB テーブルを追跡します + # たとえば、ここでファクトリを使うことができます account = FactoryBot.create(:account, name: "test") - # or with Fabrication + # あるいは Fabrication を使う account = Fabricate(:account, name: "test") - # or with plain old AR + # あるいは昔ながらの素の AR を使う account = Account.create!(name: "test") - # updates are also tracked + # 更新も追跡されます account.update!(tag: "sql-dump") end end - # Here, we MUST use a custom way to retrieve a record: since we restore the data - # from a plain SQL dump, we have no knowledge of Ruby objects + # ここでは、レコードを取得する独自の方法を使わなければなりません。データは + # 素の SQL ダンプから復元されるため、Ruby オブジェクトについては何も分からないからです let(:account) { Account.find_by!(name: "test") } end ``` -And that's what happened when we run tests: +そして、テストを実行すると次のようなことが起こります。 ```sh -# first run +# 1 回目の実行 $ bundle exec rspec -# AnyFixture.register_dump is called: -# - is SQL dump present? No -# - run block and write all modifying queries to a new SQL dump -# AnyFixture.clean is called: -# - clean all the affected tables +# AnyFixture.register_dump が呼び出される: +# - SQL ダンプは存在するか? いいえ +# - ブロックを実行し、データを変更するすべてのクエリを新しい SQL ダンプに書き出す +# AnyFixture.clean が呼び出される: +# - 影響を受けたすべてのテーブルをクリーンアップする -# second run +# 2 回目の実行 $ bundle exec rspec -# AnyFixture.register_dump is called: -# - is SQL dump present? Yes -# - restore dump (do not run block) -# AnyFixture.clean is called: -# - clean all the affected tables +# AnyFixture.register_dump が呼び出される: +# - SQL ダンプは存在するか? はい +# - ダンプを復元する (ブロックは実行しない) +# AnyFixture.clean が呼び出される: +# - 影響を受けたすべてのテーブルをクリーンアップする ``` -### Requirements +### 要件 -Currently, only PostgreSQL 12+ and SQLite3 are supported. +現在サポートされているのは PostgreSQL 12 以上と SQLite3 のみです。 -### Dump invalidation +### ダンプの無効化 -The generated dump could become out of date for many reasons: database schema changed, fixture block has been updated, etc. -To deal with invalidation, we use file content digests as _cache keys_ (dump file name suffixes). +生成されたダンプは、データベーススキーマの変更やフィクスチャのブロックの更新など、さまざまな理由で古くなることがあります。 +古くなったダンプを使わないようにするため、ファイル内容のダイジェストを _キャッシュキー_ (ダンプファイル名のサフィックス) として使っています。 -By default, AnyFixture _watches_ `db/schema.rb`, `db/structure.sql` and the file that calls `#register_dump`. +デフォルトでは、AnyFixture は `db/schema.rb`、`db/structure.sql`、および `#register_dump` を呼び出しているファイルを _監視_ します。 -The list of default watch files could be updated by modifying the `default_dump_watch_paths` configuration parameter: +デフォルトの監視対象ファイルの一覧は、設定パラメータ `default_dump_watch_paths` を変更することで更新できます。 ```ruby TestProf::AnyFixture.configure do |config| - # you can use exact file paths or globs + # 正確なファイルパスや glob を使えます config.default_dump_watch_paths << Rails.root.join("spec/factories/**/*") end ``` -Also, you add watch files to a specific `#register_dump` call via the `watch` option: +また、`watch` オプションを使って、特定の `#register_dump` の呼び出しに監視対象ファイルを追加できます。 ```ruby TestProf::AnyFixture.register_dump("account", watch: ["app/models/account.rb", "app/models/account/**/*,rb"]) do @@ -252,30 +255,30 @@ TestProf::AnyFixture.register_dump("account", watch: ["app/models/account.rb", " end ``` -**NOTE:** When you use the `watch` option, the current file is not added to the watch list. You should use `__FILE__` explicitly for that. +**注意:** `watch` オプションを使う場合、現在のファイルは監視リストに追加されません。追加するには `__FILE__` を明示的に指定してください。 -Finally, if you want to forcefully re-generate a dump, you can use the `ANYFIXTURE_FORCE_DUMP` environment variable: +最後に、ダンプを強制的に再生成したい場合は、環境変数 `ANYFIXTURE_FORCE_DUMP` を使えます。 -- `ANYFIXTURE_FORCE_DUMP=1` will force all dumps regeneration. -- `ANYFIXTURE_FORCE_DUMP=account` will force regeneration only of the matching dumps (i.e., matching `/account/`). +- `ANYFIXTURE_FORCE_DUMP=1` は、すべてのダンプを強制的に再生成します。 +- `ANYFIXTURE_FORCE_DUMP=account` は、マッチするダンプ (つまり `/account/` にマッチするもの) だけを強制的に再生成します。 -#### Cache keys +#### キャッシュキー -It's possible to provide custom cache keys to be used as a part of a digest: +ダイジェストの一部として使われる独自のキャッシュキーを指定することもできます。 ```ruby -# cache_key could be pretty much anything that responds to #to_s +# cache_key には、#to_s に応答するものならほぼ何でも指定できます TestProf::AnyFixture.register_dump("account", cache_key: ["str", 1, {key: :val}]) do # ... end ``` -### Hooks +### フック #### `before` / `after` -Before hooks are called either before calling a fixture block or before restoring a dump. -One particular use case is to re-create a tenant in a multi-tenant app: +before フックは、フィクスチャのブロックを呼び出す前、またはダンプを復元する前に呼び出されます。 +具体的なユースケースの 1 つは、マルチテナントアプリケーションでテナントを作り直すことです。 ```ruby TestProf::AnyFixture.register_dump( @@ -293,16 +296,16 @@ TestProf::AnyFixture.register_dump( end ``` -Similarly, after hooks are called either after calling a fixture block or after restoring a dump. +同様に、after フックは、フィクスチャのブロックを呼び出した後、またはダンプを復元した後に呼び出されます。 -You can also specify global before and after hooks: +グローバルな before フックと after フックを指定することもできます。 ```ruby TestProf::AnyFixture.configure do |config| config.before_dump do |dump:, import:| - # dump is an object containing information about the dump (e.g., dump.digest) - # import is true if we're restoring a dump and false otherwise - # do something + # dump はダンプに関する情報 (例: dump.digest) を持つオブジェクトです + # import は、ダンプを復元している場合は true、そうでなければ false です + # 何か処理を行う end config.after_dump do |dump:, import:| @@ -311,22 +314,22 @@ TestProf::AnyFixture.configure do |config| end ``` -**NOTE**: after callbacks are always executed, even if dump creation failed. You can use the `dump.success?` method to determine whether data generation succeeds or not. +**注意**: after コールバックは、ダンプの作成に失敗した場合でも必ず実行されます。データ生成が成功したかどうかは `dump.success?` メソッドで判定できます。 #### `skip_if` -This callback is available only as of the `#register_dump` option and could be used to ignore the fixture completely. This is useful when you want to preserve the database state between test runs (i.e., do not clean the DB). +このコールバックは `#register_dump` のオプションとしてのみ利用でき、フィクスチャを完全に無視するために使えます。テスト実行をまたいでデータベースの状態を保持したい (つまり DB をクリーンアップしない) 場合に便利です。 -Here is a complete example: +完全な例を次に示します。 ```ruby TestProf::AnyFixture.register_dump( "account", - # do not track tables for AnyFixture.clean (though other fixtures could affect this) + # AnyFixture.clean のためのテーブル追跡を行わない (ただし、他のフィクスチャが影響することはあります) clean: false, skip_if: proc do |dump:| Apartment::Tenant.switch!("test") - # if the current account has matching meta — the database is in actual state + # 現在の account がマッチする meta を持っていれば、データベースは最新の状態です Account.find_by!(name: "test").meta["dump-version"] == dump.digest end, before: proc do @@ -338,7 +341,7 @@ TestProf::AnyFixture.register_dump( Apartment::Tenant.create("test") end, after: proc do |dump:, import:| - # do not persist dump version if dump failed or we're restoring data + # ダンプに失敗した場合やデータを復元している場合は、ダンプのバージョンを保存しない next if import || !dump.success? Account.find_by!(name: "test").then do |account| @@ -351,19 +354,19 @@ TestProf::AnyFixture.register_dump( end ``` -### Configuration +### 設定 -There a few more configuration options available: +ほかにもいくつかの設定オプションがあります。 ```ruby TestProf::AnyFixture.configure do |config| - # Where to store dumps (by default, TestProf.artifact_path + '/any_dumps') + # ダンプの保存先 (デフォルトは TestProf.artifact_path + '/any_dumps') config.dumps_dir = "any_dumps" - # Include mathing queries into a dump (in addition to INSERT/UPDATE/DELETE queries) + # (INSERT/UPDATE/DELETE クエリに加えて) マッチするクエリをダンプに含める config.dump_matching_queries = /^$/ - # Whether to try using CLI tools such as psql or sqlite3 to restore dumps or not (and use ActiveRecord instead) + # ダンプの復元に psql や sqlite3 などの CLI ツールを使おうとするかどうか (false の場合は代わりに ActiveRecord を使う) config.import_dump_via_cli = false end ``` -**NOTE:** When using CLI tools to restore dumps, it's not possible to track affected tables and thus clean them via `AnyFixture.clean`. +**注意:** CLI ツールを使ってダンプを復元する場合、影響を受けたテーブルを追跡できないため、`AnyFixture.clean` でクリーンアップすることはできません。 diff --git a/docs/ja/guide/recipes/before_all.md b/docs/ja/guide/recipes/before_all.md index e91f6bb..86eeac2 100755 --- a/docs/ja/guide/recipes/before_all.md +++ b/docs/ja/guide/recipes/before_all.md @@ -1,12 +1,12 @@ # Before All -Rails has a great feature – `transactional_tests`, i.e. running each example within a transaction which is roll-backed in the end. +Rails には `transactional_tests` という優れた機能があります。これは、各 example をトランザクションの中で実行し、最後にロールバックするというものです。 -Thus no example pollutes global database state. +そのため、どの example もデータベースのグローバルな状態を汚しません。 -But what if have a lot of examples with a common setup? +しかし、共通のセットアップを持つ example がたくさんある場合はどうでしょうか? -Of course, we can do something like this: +もちろん、次のように書くことはできます。 ```ruby describe BeatleWeightedSearchQuery do @@ -17,11 +17,11 @@ describe BeatleWeightedSearchQuery do @john = create(:beatle, name: "John") end - # and about 15 examples here + # そして、ここに 15 個ほどの example が並ぶ end ``` -Or you can try `before(:all)`: +あるいは `before(:all)` を試すこともできます。 ```ruby describe BeatleWeightedSearchQuery do @@ -34,10 +34,10 @@ describe BeatleWeightedSearchQuery do end ``` -But then you have to deal with database cleaning, which can be either tricky or slow. +しかしその場合は、データベースのクリーニングに対処しなければならず、これは厄介だったり遅かったりします。 -There is a better option: we can wrap the whole example group into a transaction. -And that's how `before_all` works: +もっと良い選択肢があります。example group 全体をトランザクションで包めばよいのです。 +`before_all` はまさにそのように動作します。 ```ruby describe BeatleWeightedSearchQuery do @@ -50,22 +50,22 @@ describe BeatleWeightedSearchQuery do end ``` -That's all! +これだけです! -**NOTE**: requires RSpec >= 3.3.0. +**注意**: RSpec >= 3.3.0 が必要です。 -**NOTE**: Great superpower that `before_all` provides comes with a great responsibility. -Make sure to check the [Caveats section](#caveats) of this document for details. +**注意**: `before_all` がもたらす大いなる力には、大いなる責任が伴います。 +詳細については、このドキュメントの[注意点のセクション](#caveats)を必ず確認してください。 -## Instructions +## 使い方 -### Multiple database support +### 複数データベースのサポート -The ActiveRecord BeforeAll adapter will only start a transaction using ActiveRecord::Base connection. -If you want to ensure `before_all` can use multiple connections, you need to ensure the connection -classes are loaded before using `before_all`. +ActiveRecord の BeforeAll アダプタは、ActiveRecord::Base のコネクションを使ってのみトランザクションを開始します。 +`before_all` で複数のコネクションを使えるようにしたい場合は、`before_all` を使う前に +コネクションクラスがロードされているようにする必要があります。 -For example, imagine you have `ApplicationRecord` and a separate database for user accounts: +たとえば、`ApplicationRecord` と、ユーザーアカウント用の別のデータベースがあるとします。 ```ruby class Users < AccountsRecord @@ -77,34 +77,34 @@ class Articles < ApplicationRecord end ``` -Then those two Connection Classes do need to be loaded before the tests are run: +この場合、テストを実行する前に、これら 2 つのコネクションクラスをロードしておく必要があります。 ```ruby -# Ensure connection classes are loaded +# コネクションクラスが確実にロードされるようにする ApplicationRecord AccountsRecord ``` -This code can be added to `rails_helper.rb` or the rake tasks that runs minitests. +このコードは `rails_helper.rb` や、Minitest を実行する rake タスクに追加できます。 ### RSpec -In your `rails_helper.rb` (or `spec_helper.rb` after *ActiveRecord* has been loaded): +`rails_helper.rb` (または `spec_helper.rb` の *ActiveRecord* がロードされた後) に次の記述を追加してください。 ```ruby require "test_prof/recipes/rspec/before_all" ``` -**NOTE**: `before_all` (and `let_it_be` that depends on it), does not wrap individual -tests in a database transaction of its own. Use Rails' native `use_transactional_tests` -(`use_transactional_fixtures` in Rails < 5.1), RSpec Rails' `use_transactional_fixtures`, -DatabaseCleaner, or custom code that begins a transaction before each test and rolls it -back after. +**注意**: `before_all` (およびそれに依存する `let_it_be`) は、個々のテストを +独自のデータベーストランザクションで包むことはしません。Rails ネイティブの `use_transactional_tests` +(Rails < 5.1 では `use_transactional_fixtures`)、RSpec Rails の `use_transactional_fixtures`、 +DatabaseCleaner、あるいは各テストの前にトランザクションを開始して後でロールバックする +独自のコードを使ってください。 ### Minitest -It is possible to use `before_all` with Minitest too: +`before_all` は Minitest でも使うことができます。 ```ruby require "test_prof/recipes/minitest/before_all" @@ -119,21 +119,21 @@ class MyBeatlesTest < Minitest::Test @john = create(:beatle, name: "John") end - # define tests which could access the object defined within `before_all` + # `before_all` の中で定義したオブジェクトにアクセスできるテストを定義する end ``` -In addition to `before_all`, TestProf also provides a `after_all` callback, which is called right before the transaction open by `before_all` is closed, i.e., after the last example from the test class completes. +`before_all` に加えて、TestProf は `after_all` コールバックも提供しています。これは、`before_all` が開いたトランザクションが閉じられる直前、つまりテストクラスの最後の example が完了した後に呼び出されます。 -## Database adapters +## データベースアダプタ -You can use `before_all` not only with ActiveRecord (which is supported out-of-the-box) but with other database tools too. +`before_all` は、(標準でサポートされている) ActiveRecord だけでなく、他のデータベースツールでも使うことができます。 -All you need is to build a custom adapter and configure `before_all` to use it: +必要なのは、カスタムアダプタを作成し、それを使うように `before_all` を設定することだけです。 ```ruby class MyDBAdapter - # before_all adapters must implement two methods: + # before_all のアダプタは次の 2 つのメソッドを実装しなければなりません: # - begin_transaction # - rollback_transaction def begin_transaction @@ -145,35 +145,35 @@ class MyDBAdapter end end -# And then set adapter for `BeforeAll` module +# そして `BeforeAll` モジュールにアダプタを設定する TestProf::BeforeAll.adapter = MyDBAdapter.new ``` -## Hooks +## フック -You can register callbacks to run before/after `before_all` opens and rollbacks a transaction: +`before_all` がトランザクションを開く前後、およびロールバックする前後に実行されるコールバックを登録できます。 ```ruby TestProf::BeforeAll.configure do |config| config.before(:begin) do - # do something before transaction opens + # トランザクションが開く前に何か処理を行う end - # after(:begin) is also available + # after(:begin) も利用できます config.after(:rollback) do - # do something after transaction closes + # トランザクションが閉じた後に何か処理を行う end - # before(:rollback) is also available + # before(:rollback) も利用できます end ``` -See the example in [Discourse](https://github.com/discourse/discourse/blob/4a1755b78092d198680c2fe8f402f236f476e132/spec/rails_helper.rb#L81-L141). +[Discourse](https://github.com/discourse/discourse/blob/4a1755b78092d198680c2fe8f402f236f476e132/spec/rails_helper.rb#L81-L141) での使用例をご覧ください。 -## Caveats +## 注意点 {#caveats} -### Database is rolled back to a pristine state, but the objects are not +### データベースは元の状態にロールバックされるが、オブジェクトはされない -If you modify objects generated within a `before_all` block in your examples, you maybe have to re-initiate them: +`before_all` ブロックの中で生成したオブジェクトを example の中で変更する場合、オブジェクトを初期化し直す必要があるかもしれません。 ```ruby before_all do @@ -183,70 +183,70 @@ end let(:user) { @user } it "when user is admin" do - # we modified our object in-place! + # オブジェクトをその場で変更してしまった! user.update!(role: 1) expect(user).to be_admin end it "when user is regular" do - # now @user's state depends on the order of specs! + # こうなると @user の状態は spec の実行順序に依存する! expect(user).not_to be_admin end ``` -The easiest way to solve this is to reload record for every example (it's still much faster than creating a new one): +これを解決する最も簡単な方法は、example ごとにレコードをリロードすることです (それでも新しく作成するよりずっと高速です)。 ```ruby before_all do @user = create(:user) end -# Note, that @user.reload may not be enough, -# 'cause it doesn't reset associations +# @user.reload では不十分な場合があることに注意してください。 +# 関連付けがリセットされないためです let(:user) { User.find(@user.id) } -# or with Minitest +# あるいは Minitest の場合 def setup @user = User.find(@user.id) end ``` -### Database is not rolled back between tests +### データベースはテスト間ではロールバックされない -Database is not rolled back between RSpec examples, only between example groups. -We don't want to reinvent the wheel and encourage you to use other tools that -provide this out of the box. +`before_all` がデータベースをロールバックするのは example group の間だけで、RSpec の example の間ではロールバックしません。 +私たちは車輪の再発明をしたくないので、この機能を標準で提供している +他のツールを使うことをお勧めします。 -If you're using RSpec Rails, turn on `RSpec.configuration.use_transactional_fixtures` in your `spec/rails_helper.rb`: +RSpec Rails を使っている場合は、`spec/rails_helper.rb` で `RSpec.configuration.use_transactional_fixtures` を有効にしてください。 ```ruby RSpec.configure do |config| - config.use_transactional_fixtures = true # RSpec takes care to use `use_transactional_tests` or `use_transactional_fixtures` depending on the Rails version used + config.use_transactional_fixtures = true # RSpec は、使用している Rails のバージョンに応じて `use_transactional_tests` と `use_transactional_fixtures` を使い分けてくれます end ``` -Make sure to set `use_transactional_tests` (`use_transactional_fixtures` in Rails < 5.1) to `true` if you're using Minitest. +Minitest を使っている場合は、`use_transactional_tests` (Rails < 5.1 では `use_transactional_fixtures`) を必ず `true` に設定してください。 -If you're using DatabaseCleaner, make sure it rolls back the database between tests. +DatabaseCleaner を使っている場合は、テスト間でデータベースがロールバックされるようになっていることを確認してください。 -## Usage with Isolator +## Isolator と併用する -[Isolator](https://github.com/palkan/isolator) is a runtime detector of potential atomicity breaches within DB transactions (e.g. making HTTP calls or enqueuing background jobs). +[Isolator](https://github.com/palkan/isolator) は、DB トランザクション内でアトミック性が破られる可能性のある箇所 (HTTP 呼び出しやバックグラウンドジョブのエンキューなど) を実行時に検出するツールです。 -TestProf recognizes Isolator out-of-the-box and make it ignore `before_all` transactions. +TestProf は Isolator を標準で認識し、`before_all` のトランザクションを無視させます。 -You just need to make sure that you require `isolator` before loading `before_all` (or `let_it_be`). +必要なのは、`before_all` (または `let_it_be`) をロードする前に `isolator` を require しておくことだけです。 -Alternatively, you can load the patch explicitly: +あるいは、パッチを明示的にロードすることもできます。 ```ruby -# after loading before_all or/and let_it_be +# before_all や let_it_be をロードした後に require "test_prof/before_all/isolator" ``` -## Using Rails fixtures (_experimental_) +## Rails のフィクスチャを使う (_実験的_) -If you want to use fixtures within a `before_all` hook, you must explicitly opt-in via `setup_fixture:` option: +`before_all` フックの中でフィクスチャを使いたい場合は、`setup_fixture:` オプションで明示的にオプトインする必要があります。 ```ruby before_all(setup_fixtures: true) do @@ -255,9 +255,9 @@ before_all(setup_fixtures: true) do end ``` -Works for both Minitest and RSpec. +Minitest と RSpec の両方で動作します。 -You can also enable fixtures globally (i.e., for all `before_all` hooks): +フィクスチャをグローバルに (つまり、すべての `before_all` フックで) 有効にすることもできます。 ```ruby TestProf::BeforeAll.configure do |config| @@ -265,9 +265,9 @@ TestProf::BeforeAll.configure do |config| end ``` -## Global Tags +## グローバルタグ -You can register callbacks for specific RSpec Example Groups using tags: +タグを使って、特定の RSpec の example group に対するコールバックを登録できます。 ```ruby TestProf::BeforeAll.configure do |config| diff --git a/docs/ja/guide/recipes/factory_all_stub.md b/docs/ja/guide/recipes/factory_all_stub.md index 13d7d4a..415d487 100755 --- a/docs/ja/guide/recipes/factory_all_stub.md +++ b/docs/ja/guide/recipes/factory_all_stub.md @@ -1,28 +1,28 @@ # FactoryAllStub -_Factory All Stub_ is a spell to force FactoryBot/FactoryGirl use only `build_stubbed` strategy (even if you call `create` or `build`). +_Factory All Stub_ は、(`create` や `build` を呼び出した場合でも) FactoryBot に `build_stubbed` ストラテジーだけを使わせる呪文です。 -The idea behind it is to quickly fix [Factory Doctor](../profilers/factory_doctor.md) offenses (and even do that automatically). +その背景にある考えは、[Factory Doctor](../profilers/factory_doctor.md) が検出した違反を素早く修正する (さらには自動で修正する) ことです。 -**NOTE**. Only works with FactoryGirl/FactoryBot. Should be considered only as a temporary specs fix. +**注意**. FactoryBot でのみ動作します。あくまで spec の一時的な修正として考えてください。 -## Instructions +## 使い方 -First, you have to initialize `FactoryAllStub`: +まず、`FactoryAllStub` を初期化する必要があります。 ```ruby TestProf::FactoryAllStub.init ``` -The initialization process injects custom logic into FactoryBot generator. +この初期化処理は、FactoryBot のジェネレータに独自のロジックを注入します。 -To enable _all-stub_ mode: +_all-stub_ モードを有効にするには次のようにします。 ```ruby TestProf::FactoryAllStub.enable! ``` -To disable _all-stub_ mode and use factories as always: +_all-stub_ モードを無効にして、いつもどおりファクトリを使うには次のようにします。 ```ruby TestProf::FactoryAllStub.disable! @@ -30,29 +30,29 @@ TestProf::FactoryAllStub.disable! ## RSpec -In your `spec_helper.rb` (or `rails_helper.rb` if any): +`spec_helper.rb` (`rails_helper.rb` がある場合はそちら) に次の記述を追加してください。 ```ruby require "test_prof/recipes/rspec/factory_all_stub" ``` -That would automatically initialize `FactoryAllStub` (no need to call `.init`) and provide -`"factory:stub"` shared context with enables it for the marked examples or example groups: +これにより `FactoryAllStub` が自動的に初期化され (`.init` を呼び出す必要はありません)、 +印を付けた example や example group でこのモードを有効にする `"factory:stub"` shared context が提供されます。 ```ruby describe "User" do let(:user) { create(:user) } it "is valid", factory: :stub do - # use `build_stubbed` instead of `create` + # `create` の代わりに `build_stubbed` を使う expect(user).to be_valid end end ``` -`FactoryAllStub` was designed to be used with `FactoryDoctor` the following way: +`FactoryAllStub` は、次のように `FactoryDoctor` と組み合わせて使うことを想定して設計されています。 ```sh -# Run FactoryDoctor and mark all offensive examples with factory:stub +# FactoryDoctor を実行し、違反しているすべての example に factory:stub の印を付ける FDOC=1 FDOC_STAMP=factory:stub rspec ./spec/models ``` diff --git a/docs/ja/guide/recipes/factory_default.md b/docs/ja/guide/recipes/factory_default.md index 1310a9f..83573bd 100755 --- a/docs/ja/guide/recipes/factory_default.md +++ b/docs/ja/guide/recipes/factory_default.md @@ -1,12 +1,10 @@ # FactoryDefault -_FactoryDefault_ aims to help you cope with _factory cascades_ (see [FactoryProf](../profilers/factory_prof.md)) by reusing associated records. +_FactoryDefault_ は、関連レコードを再利用することで、_ファクトリカスケード_ ([FactoryProf](../profilers/factory_prof.md) を参照) に対処するのを助けるためのものです。 -**NOTE**. Only works with FactoryGirl/FactoryBot. +典型的な SaaS アプリケーション (あるいは階層構造を持つその他のデータ) を扱っているときに、とても役に立ちます。 -It can be very useful when you're working on a typical SaaS application (or other hierarchical data). - -Consider an example. Assume we have the following factories: +例を考えてみましょう。次のようなファクトリがあるとします。 ```ruby factory :account do @@ -28,7 +26,20 @@ factory :task do end ``` -And we want to test the `Task` model: +Fabrication の場合は次のようになります。 + +```ruby +Fabricator(:account) do +end + +Fabricator(:user) do + account +end + +# など +``` + +そして、`Task` モデルをテストしたいとします。 ```ruby describe "PATCH #update" do @@ -43,11 +54,11 @@ describe "PATCH #update" do end ``` -How many users and accounts are created per example? Two and four respectively. +example ごとに user と account はいくつ作られるでしょうか? それぞれ 2 つと 4 つです。 -And it breaks our logic (every object should belong to the same account). +そしてこれでは、すべてのオブジェクトが同じ account に属するという前提が崩れてしまいます。 -Typical workaround: +典型的な回避策は次のとおりです。 ```ruby describe "PATCH #update" do @@ -62,9 +73,9 @@ describe "PATCH #update" do end ``` -That works. And there are some cons: it's a little bit verbose and error-prone (easy to forget something). +これは動作します。しかし欠点もあります。少し冗長で、間違いを起こしやすいのです (何かを書き忘れやすい)。 -Here is how we can deal with it using FactoryDefault: +FactoryDefault を使うと、次のように対処できます。 ```ruby describe "PATCH #update" do @@ -72,10 +83,10 @@ describe "PATCH #update" do let(:project) { create_default(:project) } let(:task) { create(:task) } - # and if we need more projects, users, tasks with the same parent record, - # we just write - let(:another_project) { create(:project) } # uses the same account - let(:another_task) { create(:task) } # uses the same account + # 同じ親レコードを持つ project、user、task がさらに必要な場合は、 + # 単にこう書くだけです + let(:another_project) { create(:project) } # 同じ account を使う + let(:another_task) { create(:task) } # 同じ account を使う it "works" do patch :update, id: task.id, task: {completed: "t"} @@ -84,43 +95,59 @@ describe "PATCH #update" do end ``` -**NOTE**. This feature introduces a bit of _magic_ to your tests, so use it with caution ('cause tests should be human-readable first). Good idea is to use defaults for top-level entities only (such as tenants in multi-tenancy apps). +**注意**: この機能はテストに少しばかりの _魔法_ を持ち込むので、注意して使ってください (テストは何よりもまず人間が読めるものであるべきだからです)。デフォルトは、最上位のエンティティ (マルチテナントアプリケーションにおけるテナントなど) にだけ使うのがよいでしょう。 -## Instructions +## 使い方 -In your `spec_helper.rb`: +`spec_helper.rb` に以下を追加してください。 ```ruby require "test_prof/recipes/rspec/factory_default" ``` -This adds two new methods to FactoryBot: +これにより、FactoryBot と Fabrication の両方、またはいずれかに次のメソッドが追加されます。 -- `FactoryBot#set_factory_default(factory, object)` – use the `object` as default for associations built with `factory` +- `FactoryBot#set_factory_default(factory, object)` / `Fabricate.set_fabricate_default(factory, object)` – `factory` で組み立てられる関連に対して、`object` をデフォルトとして使います。 -Example: +例: ```ruby let(:user) { create(:user) } before { FactoryBot.set_factory_default(:user, user) } + +# trait 付きでデフォルトのファクトリを設定することもできます +FactoryBot.set_factory_default([:user, :admin], admin) + +# あるいは (v1.4 以降) +FactoryBot.set_factory_default(:user, :admin, admin) + +# 特定の属性の上書きに対してデフォルトのレコードを登録することもできます +Fabricate.set_fabricate_default(:post, post, state: "draft") ``` -- `FactoryBot#create_default(factory, *args)` – is a shortcut for `create` + `set_factory_default`. +- `FactoryBot#create_default(...)` / `Fabricate.create_default(...)` – `create` + `set_factory_default` のショートカットです。 + +- `FactoryBot#get_factory_default(factory)` / `Fabricate.get_fabricate_default(factory)` – `factory` のデフォルト値を取得します (v1.4 以降)。 + +```rb +# このメソッドは trait にも対応しています +admin = FactoryBot.get_factory_default(:user, :admin) +``` -**IMPORTANT:** Defaults are **cleaned up after each example** by default (i.e., when using `test_prof/recipes/rspec/factory_default`). +**重要:** デフォルトは、標準では (つまり `test_prof/recipes/rspec/factory_default` を使っている場合は) **各 example の後にクリーンアップされます**。 -### Using with `before_all` / `let_it_be` +### `before_all` / `let_it_be` と一緒に使う -Defaults created within `before_all` and `let_it_be` are not reset after each example, but only at the end of the corresponding example group. So, it's possible to call `create_default` within `let_it_be` without any additional configuration. **RSpec only** +`before_all` と `let_it_be` の中で作られたデフォルトは、各 example の後にはリセットされず、対応する example group の終わりでのみリセットされます。そのため、追加の設定なしで `let_it_be` の中から `create_default` を呼び出すことができます。**RSpec のみ** -**IMPORTANT:** You must load FactoryDefault after loading BeforeAll to make this feature work. +**重要:** この機能を動作させるには、BeforeAll を読み込んだ後で FactoryDefault を読み込む必要があります。 -**NOTE**. Regular `before(:all)` callbacks are not supported. +**注意**: 通常の `before(:all)` コールバックには対応していません。 -### Working with traits +### trait を扱う -You can use traits in your associations, for example: +関連の中で trait を使うことができます。たとえば次のとおりです。 ```ruby factory :comment do @@ -136,37 +163,37 @@ factory :view do end ``` -If there is a default value for the `user` factory, it's gonna be used independently of traits. This may break your logic. +`user` ファクトリにデフォルト値がある場合、trait に関係なくそれが使われます。これはロジックを壊してしまうかもしれません。 -To prevent this, configure FactoryDefault to preserve traits: +これを防ぐには、trait を区別するように FactoryDefault を設定してください。 ```ruby -# Globally +# グローバルに TestProf::FactoryDefault.configure do |config| config.preserve_traits = true end -# or in-place +# あるいは、その場で create_default(:user, preserve_traits: true) ``` -Creating a default with trait works as follows: +trait 付きでデフォルトを作成すると、次のように動作します。 ```ruby -# Create a default with trait +# trait 付きでデフォルトを作成する user = create_default(:user_poster, :able_to_post) -# When an association has no traits specified, the default with trait is used +# 関連に trait が指定されていない場合は、trait 付きのデフォルトが使われます create(:comment).user == user #=> true -# When an association has the matching trait specified, the default is used, too +# 関連に一致する trait が指定されている場合も、デフォルトが使われます create(:post).user == user #=> true -# When the association's trait differs, default is skipped +# 関連の trait が異なる場合、デフォルトはスキップされます create(:view).user == user #=> false ``` -### Handling attribute overrides +### 属性の上書きを扱う -It's possible to define attribute overrides for associations: +関連に対して属性の上書きを定義することができます。 ```ruby factory :post do @@ -178,23 +205,23 @@ factory :view do end ``` -FactoryDefault ignores such overrides and still returns a default `user` record (if created). You can turn the attribute awareness feature on to skip the default record if overrides don't match the default object attributes: +FactoryDefault はこのような上書きを無視し、(作成済みであれば) デフォルトの `user` レコードを返します。属性を考慮する機能を有効にすると、上書きがデフォルトのオブジェクトの属性と一致しない場合に、デフォルトのレコードをスキップできます。 ```ruby -# Globally +# グローバルに TestProf::FactoryDefault.configure do |config| config.preserve_attributes = true end -# or in-place +# あるいは、その場で create_default :user, preserve_attributes: true ``` -**NOTE:** In the future versions of Test Prof, both `preserve_traits` and `preserve_attributes` will default to true. We recommend settings them to true if you just starting using this feature. +**注意:** TestProf の将来のバージョンでは、`preserve_traits` と `preserve_attributes` の両方がデフォルトで true になります。この機能を使い始めたばかりであれば、これらを true に設定することをお勧めします。 -### Ignoring default factories +### デフォルトのファクトリを無視する -You can temporary disable the defaults usage by wrapping a code with the `skip_factory_default` method: +コードを `skip_factory_default` メソッドで囲むことで、デフォルトの使用を一時的に無効にできます。 ```ruby account = create_default(:account) @@ -203,19 +230,19 @@ another_account = skip_factory_default { create(:account) } expect(another_account).not_to eq(account) ``` -### Showing usage stats +### 使用状況の統計を表示する -You can display the FactoryDefault usage stats by setting the `FACTORY_DEFAULT_SUMMARY=1` or `FACTORY_DEFAULT_STATS=1` env vars or by setting the configuration values: +環境変数 `FACTORY_DEFAULT_SUMMARY=1` または `FACTORY_DEFAULT_STATS=1` を設定するか、設定値を指定することで、FactoryDefault の使用状況の統計を表示できます。 ```ruby TestProf::FactoryDefault.configure do |config| config.report_summary = true - # Report stats prints the detailed usage information (including summary) + # report_stats は詳細な使用状況 (サマリーを含む) を出力します config.report_stats = true end ``` -For example: +たとえば次のとおりです。 ```sh $ FACTORY_DEFAULT_SUMMARY=1 bundle exec rspec @@ -223,13 +250,13 @@ $ FACTORY_DEFAULT_SUMMARY=1 bundle exec rspec FactoryDefault summary: hit=11 miss=3 ``` -Where `hit` indicates the number of times the default factory value was used instead of a new one when an association was created; `miss` indicates the number of time the default value was ignored due to traits or attributes mismatch. +ここで `hit` は、関連が作られる際に、新しい値の代わりにデフォルトのファクトリの値が使われた回数を示します。`miss` は、trait や属性の不一致によってデフォルト値が無視された回数を示します。 -## Factory Default profiling, or when to use defaults +## FactoryDefault のプロファイリング、あるいはデフォルトをいつ使うべきか -Factory Default ships with the profiler, which can help you to see how associations are being used in your test suite, so you can decide on using `create_default` or not. +FactoryDefault にはプロファイラが付属しています。テストスイートの中で関連がどのように使われているかを確認できるので、`create_default` を使うかどうかを判断するのに役立ちます。 -To enable profiling, run your tests with the `FACTORY_DEFAULT_PROF=1` set: +プロファイリングを有効にするには、`FACTORY_DEFAULT_PROF=1` を設定してテストを実行してください。 ```sh $ FACTORY_DEFAULT_PROF=1 bundle exec rspec spec/some/file_spec.rb @@ -249,6 +276,6 @@ Total uniq associations created: 3 Total time spent: 01:13.775 ``` -Since default factories are usually registered per an example group (or test class), we recommend running this profiler against a particular file, so you can quickly identify the possibility of adding `create_default` and improve the tests speed. +デフォルトのファクトリは通常、example group (またはテストクラス) ごとに登録されるので、このプロファイラは特定のファイルに対して実行することをお勧めします。そうすれば、`create_default` を追加できる箇所をすばやく見つけ、テストの速度を改善できます。 -**NOTE:** You can also use the profiler to measure the effect of adding `create_default`; for that, compare the results of running the profiler with FactoryDefault enabled and disabled (you can do that by passing the `FACTORY_DEFAULT_DISABLED=1` env var). +**注意:** このプロファイラは、`create_default` を追加した効果を測るためにも使えます。そのためには、FactoryDefault を有効にした場合と無効にした場合のプロファイラの実行結果を比較してください (環境変数 `FACTORY_DEFAULT_DISABLED=1` を渡すことで無効にできます)。 diff --git a/docs/ja/guide/recipes/let_it_be.md b/docs/ja/guide/recipes/let_it_be.md index 7eaad8c..a434b2b 100755 --- a/docs/ja/guide/recipes/let_it_be.md +++ b/docs/ja/guide/recipes/let_it_be.md @@ -1,8 +1,8 @@ # Let It Be -Let's bring a little bit of magic and introduce a new way to set up a _shared_ test data. +少しばかりの魔法を持ち込んで、_共有_ のテストデータをセットアップする新しい方法を紹介しましょう。 -Suppose you have the following setup: +次のようなセットアップがあるとします。 ```ruby describe BeatleWeightedSearchQuery do @@ -13,13 +13,13 @@ describe BeatleWeightedSearchQuery do specify { expect(subject.call("john")).to contain_exactly(john) } - # and more examples here + # さらに example が続きます end ``` -We don't need to re-create the Fab Four for every example, do we? +example ごとに Fab Four を作り直す必要はありませんよね? -We already have [`before_all`](./before_all.md) to solve the problem of _repeatable_ data: +_繰り返し使える_ データを example ごとに作り直してしまう問題を解決するものとして、すでに [`before_all`](./before_all.md) があります。 ```ruby describe BeatleWeightedSearchQuery do @@ -34,9 +34,9 @@ describe BeatleWeightedSearchQuery do end ``` -That technique works pretty good but requires us to use instance variables and define everything at once. Thus it's not easy to refactor existing tests which use `let/let!` instead. +この手法はかなりうまく動作しますが、インスタンス変数を使い、すべてを一度に定義する必要があります。そのため、代わりに `let/let!` を使っている既存のテストをリファクタリングするのは簡単ではありません。 -With `let_it_be` you can do the following: +`let_it_be` を使うと、次のように書けます。 ```ruby describe BeatleWeightedSearchQuery do @@ -47,24 +47,24 @@ describe BeatleWeightedSearchQuery do specify { expect(subject.call("john")).to contain_exactly(john) } - # and more examples here + # さらに example が続きます end ``` -That's it! Just replace `let!` with `let_it_be`. That's equal to the `before_all` approach but requires less refactoring. +これだけです! `let!` を `let_it_be` に置き換えるだけです。これは `before_all` を使う方法と同等ですが、必要なリファクタリングは少なくて済みます。 -**NOTE**: Great superpower that `before_all` provides comes with a great responsibility. -Make sure to check the [Caveats section](#caveats) of this document for details. +**注意**: `before_all` がもたらす大いなる力には、大いなる責任が伴います。 +詳細については、このドキュメントの[注意点のセクション](#caveats)を必ず確認してください。 -## Instructions +## 使い方 -In your `rails_helper.rb` or `spec_helper.rb`: +`rails_helper.rb` または `spec_helper.rb` に以下を追加してください。 ```ruby require "test_prof/recipes/rspec/let_it_be" ``` -In your tests: +テストでは次のように書きます。 ```ruby describe MySuperDryService do @@ -74,139 +74,139 @@ describe MySuperDryService do end ``` -`let_it_be` won't automatically bring the database to its previous state between -the examples, it only does that between example groups. -Use Rails' native `use_transactional_tests` (`use_transactional_fixtures` in Rails < 5.1), -RSpec Rails' `use_transactional_fixtures`, DatabaseCleaner, or custom code that -begins a transaction before each test and rolls it back after. +`let_it_be` は、example の間でデータベースを自動的に以前の状態へ戻すことはしません。 +それを行うのは example group の間だけです。 +Rails 標準の `use_transactional_tests` (Rails < 5.1 では `use_transactional_fixtures`)、 +RSpec Rails の `use_transactional_fixtures`、DatabaseCleaner、あるいは +各テストの前にトランザクションを開始し、後でロールバックする独自のコードを使ってください。 -## Caveats +## 注意点 {#caveats} -### Database is rolled back to a pristine state, but the objects are not +### データベースは元の状態にロールバックされるが、オブジェクトはされない -If you modify objects generated within a `let_it_be` block in your examples, you maybe have to re-initiate them. -We have a built-in _modifiers_ support for that. +`let_it_be` ブロックの中で生成したオブジェクトを example の中で変更する場合、それらを再初期化する必要があるかもしれません。 +そのために、組み込みの _モディファイア_ を用意しています。 -### Database is not rolled back between tests +### テストの間でデータベースはロールバックされない -Database is not rolled back between RSpec examples, only between example groups. -We don't want to reinvent the wheel and encourage you to use other tools that -provide this out of the box. +データベースは RSpec の example の間ではロールバックされず、example group の間でのみロールバックされます。 +私たちは車輪の再発明をしたくないので、これを標準で提供している他のツールを +使うことをお勧めします。 -If you're using RSpec Rails, turn on `RSpec.configuration.use_transactional_fixtures` in your `spec/rails_helper.rb`: +RSpec Rails を使っている場合は、`spec/rails_helper.rb` で `RSpec.configuration.use_transactional_fixtures` を有効にしてください。 ```ruby RSpec.configure do |config| - config.use_transactional_fixtures = true # RSpec takes care to use `use_transactional_tests` or `use_transactional_fixtures` depending on the Rails version used + config.use_transactional_fixtures = true # 使用している Rails のバージョンに応じて、RSpec が `use_transactional_tests` と `use_transactional_fixtures` を使い分けてくれます end ``` -Make sure to set `use_transactional_tests` (`use_transactional_fixtures` in Rails < 5.1) to `true` if you're using Minitest. +Minitest を使っている場合は、`use_transactional_tests` (Rails < 5.1 では `use_transactional_fixtures`) を必ず `true` に設定してください。 -If you're using DatabaseCleaner, make sure it rolls back the database between tests. +DatabaseCleaner を使っている場合は、テストの間でデータベースがロールバックされるようにしてください。 -## Aliases +## エイリアス -Naming is hard. Handling edge cases (the ones described above) is also tricky. +名前を付けるのは難しいものです。(上で述べたような) エッジケースを扱うのもやっかいです。 -To solve this we provide a way to define `let_it_be` aliases with the predefined options: +これを解決するために、あらかじめ決めたオプションを持つ `let_it_be` のエイリアスを定義する方法を用意しています。 ```ruby # rails_helper.rb TestProf::LetItBe.configure do |config| - # define an alias with `refind: true` by default + # デフォルトで `refind: true` となるエイリアスを定義する config.alias_to :let_it_be_with_refind, refind: true end -# then use it in your tests +# そして、テストの中でそれを使う describe "smth" do let_it_be_with_refind(:foo) { Foo.create } - # refind can still be overridden + # それでも refind は上書きできる let_it_be_with_refind(:bar, refind: false) { Bar.create } end ``` -## Modifiers +## モディファイア -If you modify objects generated within a `let_it_be` block in your examples, you maybe have to re-initiate them to avoid state leakage between the examples. -Keep in mind that even though the database is rolled back to its pristine state, models themselves are not. +`let_it_be` ブロックの中で生成したオブジェクトを example の中で変更する場合、example 間で状態が持ち越されるのを避けるために、それらを再初期化する必要があるかもしれません。 +データベースが元の状態にロールバックされても、モデル自体は元に戻らないことを覚えておいてください。 -We have a built-in _modifiers_ support for getting models to their pristine state: +モデルを元の状態に戻すために、組み込みの _モディファイア_ を用意しています。 ```ruby -# Use reload: true option to reload user object (assuming it's an instance of ActiveRecord) -# for every example +# reload: true オプションを使うと、example ごとに user オブジェクトを +# リロードします (ActiveRecord のインスタンスであることを想定) let_it_be(:user, reload: true) { create(:user) } -# it is almost equal to +# これは次のコードとほぼ同等です before_all { @user = create(:user) } let(:user) { @user.reload } -# You can also specify refind: true option to hard-reload the record +# refind: true オプションを指定して、レコードを完全に読み込み直すこともできます let_it_be(:user, refind: true) { create(:user) } -# it is almost equal to +# これは次のコードとほぼ同等です before_all { @user = create(:user) } let(:user) { User.find(@user.id) } ``` -**NOTE:** make sure that you require `let_it_be` after `active_record` is loaded (e.g., in `rails_helper.rb` **after** requiring the Rails app); otherwise the `refind` and `reload` modifiers are not activated. +**注意:** `let_it_be` は、必ず `active_record` が読み込まれた後で require してください (たとえば、`rails_helper.rb` の中で Rails アプリケーションを require した**後**)。そうしないと、`refind` と `reload` のモディファイアは有効になりません。 -You can also use modifiers with array values, e.g. `create_list`: +モディファイアは、`create_list` のような配列の値に対しても使えます。 ```ruby let_it_be(:posts, reload: true) { create_list(:post, 3) } -# it's the same as +# これは次のコードと同じです before_all { @posts = create_list(:post, 3) } let(:posts) { @posts.map(&:reload) } ``` -### Custom Modifiers +### カスタムモディファイア -If `reload` and `refind` is not enough, you can add your custom modifier: +`reload` と `refind` だけでは足りない場合は、独自のモディファイアを追加できます。 ```ruby # rails_helper.rb TestProf::LetItBe.configure do |config| - # Define a block which will be called when you access a record first within an example. - # The first argument is the pre-initialized record, - # the second is the value of the modifier. + # example の中でレコードに最初にアクセスしたときに呼び出されるブロックを定義します。 + # 第 1 引数は初期化済みのレコード、 + # 第 2 引数はモディファイアの値です。 # - # This is how `reload` modifier is defined + # `reload` モディファイアは次のように定義されています config.register_modifier :reload do |record, val| - # ignore when `reload: false` + # `reload: false` の場合は無視する next record unless val - # ignore non-ActiveRecord objects + # ActiveRecord 以外のオブジェクトは無視する next record unless record.is_a?(::ActiveRecord::Base) record.reload end end ``` -### Default Modifiers +### デフォルトのモディファイア -It's possible to configure the default modifiers used for all `let_it_be` calls: +すべての `let_it_be` の呼び出しで使われるデフォルトのモディファイアを設定できます。 -- Globally: +- グローバルに: ```ruby TestProf::LetItBe.configure do |config| - # Make refind activated by default + # refind をデフォルトで有効にする config.default_modifiers[:refind] = true end ``` -- For specific contexts using tags: +- タグを使って特定のコンテキストに対して: ```ruby context "with let_it_be reload", let_it_be_modifiers: {reload: true} do - # examples + # example end ``` -**NOTE:** Nested contexts tags are overwritten not merged: +**注意:** ネストしたコンテキストのタグはマージされず、上書きされます。 ```ruby TestProf::LetItBe.configure do |config| @@ -214,44 +214,46 @@ TestProf::LetItBe.configure do |config| end context "with reload", let_it_be_modifiers: {reload: true} do - # uses freeze: false, reload: true here + # ここでは freeze: false, reload: true が使われる context "with freeze", let_it_be_modifiers: {freeze: true} do - # uses only freeze: true (reload: true is overwritten by new metadata) + # freeze: true だけが使われる (reload: true は新しいメタデータで上書きされる) end end ``` -## State Leakage Detection +## 状態の持ち越しの検出 -From [`rspec-rails` docs](https://relishapp.com/rspec/rspec-rails/v/3-9/docs/transactions) on transactions and `before(:context)`: +[`rspec-rails` のドキュメント](https://relishapp.com/rspec/rspec-rails/v/3-9/docs/transactions)には、トランザクションと `before(:context)` について次のように書かれています。 > Even though database updates in each example will be rolled back, the object won't know about those rollbacks so the object and its backing data can easily get out of sync. +> +> (各 example でのデータベースの更新はロールバックされますが、オブジェクトはそのロールバックを知らないため、オブジェクトとその裏にあるデータは簡単に食い違ってしまいます。) -Since `let_it_be` initialize objects in `before(:context)` hooks under the hood, it's affected by this problem: the code might modify models shared between examples (thus causing _shared state leaks_). That could happen unwillingly: when the underlying code under test modifies models, e.g. modifies `updated_at` attribute; or deliberately: when models are updated in `before` hooks or examples themselves instead of creating models in a proper state initially. +`let_it_be` は内部的に `before(:context)` フックの中でオブジェクトを初期化するので、この問題の影響を受けます。つまり、example の間で共有されているモデルをコードが変更してしまうかもしれません (その結果、_共有状態の持ち越し_ が起こります)。これは意図せずに起こることがあります。たとえば、テスト対象のコードがモデルを変更する場合 (`updated_at` 属性を変更するなど) です。あるいは意図的に起こることもあります。最初から適切な状態でモデルを作る代わりに、`before` フックや example 自体の中でモデルを更新する場合です。 -This state leakage comes with potentially harmful side effects on the other examples, such as implicit dependencies and execution order dependency. +この状態の持ち越しは、暗黙の依存関係や実行順序への依存といった、他の example に対する有害になりうる副作用を伴います。 -With many shared models between many examples, it's hard to track down the example and exact place in the code that modifies the model. +多くの example の間で多くのモデルが共有されていると、モデルを変更している example とコード上の正確な場所を突き止めるのは困難です。 -To detect modifications, objects that are passed to `let_it_be` are frozen (with `#freeze`), and `FrozenError` is raised: +変更を検出するために、`let_it_be` で定義したオブジェクトは (`#freeze` で) フリーズされ、変更しようとすると `FrozenError` が発生します。 ```ruby -# use freeze: true modifier to enable this feature +# この機能を有効にするには freeze: true モディファイアを使います let_it_be(:user, freeze: true) { create(:user) } -# it is almost equal to +# これは次のコードとほぼ同等です before_all { @user = create(:user).freeze } let(:user) { @user } ``` -To fix the `FrozenError`: +`FrozenError` を修正するには、次のようにします。 -- Add `reload: true`/`refind: true`, it pacifies leakage detection and prevents leakage itself. Typically it's significantly faster to reload the model than to re-create it from scratch before each example (two or even three orders of magnitude faster in some cases). -- Rewrite the problematic test code. +- `reload: true`/`refind: true` を追加する。これにより検出のエラーが出なくなり、状態の持ち越しそのものも防げます。通常、各 example の前にモデルをゼロから作り直すよりも、リロードするほうがはるかに高速です (場合によっては 2 桁、あるいは 3 桁も速くなります)。 +- 問題のあるテストコードを書き直す。 -This feature is opt-in, since it may find a significant number of leakages in specs that may be a significant burden to fix all at once. -It's possible to gradually turn it on for parts of specs (e.g., only models) by using: +この機能はオプトインです。spec の中で相当な数の持ち越しが見つかり、それらを一度にすべて修正するのは大きな負担になりうるからです。 +次のようにすることで、spec の一部 (たとえばモデルだけ) に対して段階的に有効にできます。 ```ruby # spec/spec_helper.rb @@ -263,6 +265,39 @@ RSpec.configure do |config| end ``` -And then tag contexts/examples with `:let_it_be_frost` to enable this feature. +そのうえで、コンテキストや example に `:let_it_be_frost` タグを付けて、この機能を有効にします。 -Alternatively, you can specify `freeze` modifier explicitly (`let_it_be(freeze: true)`) or configure an alias. +あるいは、`freeze` モディファイアを明示的に指定する (`let_it_be(freeze: true)`) か、エイリアスを設定することもできます。 + +## 重複のレポート + +私たちは `let!` の代わりに `let_it_be` を使うことを提案していますが、重要な違いが 1 つあります。`let!` の定義は同じコンテキストやネストしたコンテキストで上書きでき、その場合は後者だけが呼び出されます。一方、`let_it_be` の定義も上書きできますが、上書きされた側のレコードも作られます。たとえば次のとおりです。 + +```ruby +context "A" do + let!(:user) { create(:user, name: "a") } + let_it_be(:post) { create(:post, title: "A") } + + specify { expect(User.all.pluck(:name)).to eq ["a"] } + specify { expect(Post.all.pluck(:title)).to eq ["A"] } + + context "B" do + let!(:user) { create(:user, name: "b") } + let_it_be(:post) { create(:post, title: "B") } + + specify { expect(User.all.pluck(:name)).to eq ["b"] } + specify { expect(Post.all.pluck(:title)).to eq ["B"] } # post が 2 つあるため失敗する + end +end +``` + +そこで、let_it_be が上書きされたときの振る舞いを設定できるようにしています。 + +```ruby +TestProf::LetItBe.configure do |config| + config.report_duplicates = :warn # Rspec.warn_with + config.report_duplicates = :raise # Kernel.raise +end +``` + +デフォルトでは、このパラメータは無効になっています。警告を出すか、例外を発生させるかの振る舞いを設定できます。 diff --git a/docs/ja/guide/recipes/logging.md b/docs/ja/guide/recipes/logging.md index 7904933..1628aba 100755 --- a/docs/ja/guide/recipes/logging.md +++ b/docs/ja/guide/recipes/logging.md @@ -1,55 +1,55 @@ -# Verbose Logging +# 詳細なロギング -Sometimes digging through logs is the best way to figure out what's going on. +何が起きているのかを突き止めるには、ログを掘り返すのが一番よい方法であることがあります。 -When you run your test suite, logs are not printed out by default (although written to `test.log` – who cares?). +テストスイートを実行しても、デフォルトではログは出力されません (`test.log` には書き込まれていますが、誰が気にするでしょうか?)。 -We provide a recipe to turn verbose logging for a specific example/group. +特定の example や group に対して詳細なロギングを有効にするレシピを用意しています。 -**NOTE:** Rails only. +**注意:** Rails のみ。 -## Instructions +## 使い方 -Drop this line to your `rails_helper.rb` / `spec_helper.rb` / `test_helper.rb` / whatever: +`rails_helper.rb` / `spec_helper.rb` / `test_helper.rb` などに、次の 1 行を追加してください。 ```ruby require "test_prof/recipes/logging" ``` -### Log everything +### すべてをログに出力する -To turn on logging globally use `LOG` env variable: +ロギングをグローバルに有効にするには、環境変数 `LOG` を使います。 ```sh -# log everything to stdout +# すべてを標準出力にログ出力する LOG=all rspec ... -# or +# あるいは LOG=all rake test -# log only Active Record statements +# Active Record のステートメントだけをログ出力する LOG=ar rspec ... ``` -### Per-example logging +### example ごとのロギング -**NOTE:** RSpec only. +**注意:** RSpec のみ。 -Activate logging by adding special tag – `:log`: +特別なタグ `:log` を追加して、ロギングを有効にします。 ```ruby -# Add the tag and you will see a lot of interesting stuff in your console +# タグを追加すると、コンソールに興味深いものがたくさん表示されます it "does smthng weird", :log do # ... end -# or for the group +# あるいは、group に対して describe "GET #index", :log do # ... end ``` -To enable only Active Record log use `log: :ar` tag: +Active Record のログだけを有効にするには、`log: :ar` タグを使います。 ```ruby describe "GET #index", log: :ar do @@ -57,22 +57,22 @@ describe "GET #index", log: :ar do end ``` -### Logging helpers +### ロギングのヘルパー -For more granular control you can use `with_logging` (log everything) and -`with_ar_logging` (log Active Record) helpers: +より細かく制御するには、`with_logging` (すべてをログ出力する) と +`with_ar_logging` (Active Record をログ出力する) のヘルパーを使えます。 ```ruby it "does somthing" do do_smth - # show logs only for the code within the block + # ブロック内のコードについてのみログを表示する with_logging do # ... end end ``` -**NOTE:** in order to use this helpers with Minitest you should include the `TestProf::Rails::LoggingHelpers` module manually: +**注意:** これらのヘルパーを Minitest で使うには、`TestProf::Rails::LoggingHelpers` モジュールを手動で include する必要があります。 ```ruby class MyLoggingTest < Minitest::Test diff --git a/docs/ja/guide/recipes/rspec_stamp.md b/docs/ja/guide/recipes/rspec_stamp.md index 4ff8e16..0764a8a 100755 --- a/docs/ja/guide/recipes/rspec_stamp.md +++ b/docs/ja/guide/recipes/rspec_stamp.md @@ -1,20 +1,20 @@ # RSpecStamp -RSpecStamp is a tool to automatically _tag_ failed examples with custom tags. +RSpecStamp は、失敗した example に独自のタグを自動的に _付ける_ ツールです。 -It _literally_ adds tags to your examples (i.e. rewrites them). +example に _文字どおり_ タグを追加します (つまり、example を書き換えます)。 -The main purpose of RSpecStamp is to make testing codebase refactoring easy. Changing global configuration may cause a lot of failures. You can patch failing spec by adding a shared context. And here comes RSpecStamp. +RSpecStamp の主な目的は、テストコードベースのリファクタリングを簡単にすることです。グローバルな設定を変更すると、大量の失敗が発生することがあります。失敗する spec には、shared context を追加することで手当てできます。そこで RSpecStamp の出番です。 -## Example Use Case: Sidekiq Inline +## ユースケースの例: Sidekiq Inline -Using `Sidekiq::Testing.inline!` may be considered a _bad practice_ (see [here](https://github.com/mperham/sidekiq/issues/3495)) due to its negative performance impact. But it's still widely used. +`Sidekiq.testing!(:inline)` を使うことは、パフォーマンスへの悪影響があるため、_バッドプラクティス_ と見なされることがあります ([こちら](https://github.com/mperham/sidekiq/issues/3495)を参照)。それでも、いまだに広く使われています。 -How to migrate from `inline!` to `fake!`? +`inline!` から `fake!` へ移行するにはどうすればよいでしょうか? -Step 0. Make sure that all your tests pass. +ステップ 0. すべてのテストが通ることを確認します。 -Step 1. Create a shared context to conditionally turn on `inline!` mode: +ステップ 1. 条件付きで `inline!` モードを有効にする shared context を作成します。 ```ruby shared_context "sidekiq:inline", sidekiq: :inline do @@ -22,28 +22,28 @@ shared_context "sidekiq:inline", sidekiq: :inline do end ``` -Step 2. Turn on `fake!` mode globally. +ステップ 2. `fake!` モードをグローバルに有効にします。 -Step 3. Run `RSTAMP=sidekiq:inline rspec`. +ステップ 3. `RSTAMP=sidekiq:inline rspec` を実行します。 -The output of the command above contains information about the _stamping_ process: +上のコマンドの出力には、_スタンプ_ の処理についての情報が含まれます。 -- How many files have been affected? +- いくつのファイルが影響を受けたか? -- How many patches were made? +- いくつのパッチが作られたか? -- How many patches failed? +- いくつのパッチが失敗したか? -- How many files have been ignored? +- いくつのファイルが無視されたか? -Now all (or almost all) failing specs are tagged with `sidekiq: :inline`. Run the whole suite again and check it there are any failures left. +これで、失敗する spec のすべて (あるいはほぼすべて) に `sidekiq: :inline` のタグが付きました。スイート全体をもう一度実行し、失敗が残っていないか確認してください。 -There is also a `dry-run` mode (activated by `RSTAMP_DRY_RUN=1` env variable) which prints out patches instead of re-writing files. +`dry-run` モード (環境変数 `RSTAMP_DRY_RUN=1` で有効になります) もあり、ファイルを書き換える代わりにパッチを出力します。 -## Configuration +## 設定 -By default, RSpecStamp ignores examples located in `spec/support` directory (typical place to put shared examples in). -You can add more _ignore_ patterns: +デフォルトでは、RSpecStamp は `spec/support` ディレクトリ (shared example を置く典型的な場所) にある example を無視します。 +_無視する_ パターンを追加することもできます。 ```ruby TestProf::RSpecStamp.configure do |config| diff --git a/docs/ja/guide/recipes/tests_sampling.md b/docs/ja/guide/recipes/tests_sampling.md index 1fe5580..acd4112 100755 --- a/docs/ja/guide/recipes/tests_sampling.md +++ b/docs/ja/guide/recipes/tests_sampling.md @@ -1,36 +1,36 @@ -# Tests Sampling +# テストのサンプリング -Sometimes it's useful to run profilers against randomly chosen tests. Unfortunately, test frameworks don't support such functionality. That's why we've included small patches for RSpec and Minitest in TestProf. +ランダムに選んだテストに対してプロファイラを実行すると役に立つことがあります。残念ながら、テストフレームワークはそのような機能をサポートしていません。そこで、RSpec と Minitest のための小さなパッチを TestProf に含めました。 -## Instructions +## 使い方 -Require the corresponding patch: +対応するパッチを require してください。 ```ruby -# For RSpec in your spec_helper.rb +# RSpec の場合は spec_helper.rb に require "test_prof/recipes/rspec/sample" -# For Minitest in your test_helper.rb +# Minitest の場合は test_helper.rb に require "test_prof/recipes/minitest/sample" ``` -And then just add `SAMPLE` env variable with the number examples you want to run: +そして、実行したい example の数を環境変数 `SAMPLE` に指定するだけです。 ```sh SAMPLE=10 rspec ``` -You can also run random set of example groups (or suites) using `SAMPLE_GROUPS` variable: +`SAMPLE_GROUPS` 変数を使って、example group (またはスイート) をランダムに選んで実行することもできます。 ```sh SAMPLE_GROUPS=10 rspec ``` -Note that you can use tests sampling with RSpec filters: +テストのサンプリングは、RSpec のフィルタと一緒に使えることも覚えておいてください。 ```sh SAMPLE=10 rspec --tag=api SAMPLE_GROUPS=10 rspec -e api ``` -That's it. Enjoy! +これだけです。お楽しみください!