Fixrb

Fix 1ガイド

Railsアプリケーションで使う

RailsアプリケーションのモデルとコントローラーをFixでテストするために必要なもの、そしてファイルの置き場所。

このページでは、Fixだけをテストフレームワークとして使う小さなマイクロブログ、fixrb/microblogというRailsアプリケーションを使います。ユーザーはハンドルを選び、短い文章を投稿し、互いにフォローし、タイムラインを読みます。ドメイン、つまりハンドルと投稿の本文はlibにある素のRubyで、プロジェクトで使うで示したとおりにテストされています。このページで扱うのは残りの部分、データベースを必要とするモデルと、アプリケーションを必要とするコントローラーです。

ここに示すファイルは、そのアプリケーションのリポジトリにあるとおりのもので、そちらでアプリケーションとともに実行されています。このサイトのリポジトリはページを公開する前に例を実行しますが、Railsをもたないため、これらは実行せずに示している例です。

Gemfile

Fixとそのコマンドは、require: falseをつけてtestグループに入れます(gem "fix", require: falseとgem "fix-command", require: false)。Railsはアプリケーションの起動時に、その環境のグループのgemをrequireします。fixのファイルは自分でFixをrequireするので、アプリケーションがFixを読み込むことはありません。

配置

モデルやコントローラーの仕様は、Railsのものを何も名指ししません(eq 302、eq ["Body can't be blank"])。そこでこのアプリケーションは、パターンが共有する仕様でそうしているように、仕様をテストから切り離しています。specには仕様を置きます。1ファイルにひとつのFix :Name do … endという文書で、それぞれFixだけをrequireし、Railsもデータベースも、対象のクラスさえも読み込みません。fixにはテスト、つまりfixコマンドが実行するファイルを置きます。それぞれがサブジェクトに必要なものを読み込み、仕様をrequireし、exit(Fix[:Name].test { … })で終わります。そのブロックがサブジェクトを作ります。こうすると、結果は仕様の行を指します。

仕様のletは、2つのファイルの間のインターフェースです。仕様はサブジェクトのパラメーターを、その既定値と、それを変えるwithとともに宣言し、テストのブロックはそれを名前で読みます。これまでのページのように両方をひとつのファイルに書いても、同じように動きます。RSpecも使うアプリケーションでは、specをRSpecのために残し、文書はたとえばfix/specsに置きます。

アプリケーションの読み込み

モデルとコントローラーのテストはヘルパーfix/support/rails.rbを共有します。名前が_fix.rbで終わらないので、fixがそれを単独で実行することはありません。

# frozen_string_literal: true

# Loads the application in its test environment, for the tests of the
# models and of the controllers. Those of the domain, in fix/microblog,
# need none of this: they run on plain Ruby. The specifications, in
# spec, need nothing but Fix.
#
# The tests empty the database, so they run in the test environment and
# nowhere else, whatever the shell says.
ENV["RAILS_ENV"] = "test"

require_relative "../../config/environment"
require "rack/test"

# Keeps the test database in step with db/schema.rb, as rails/test_help
# does.
ActiveRecord::Migration.maintain_test_schema!

# Fix builds the subject anew for every expectation, in the child
# process of its context, which gets a connection of its own: Active
# Record forgets the pool of the parent after a fork. The database
# itself is outside the processes, so a subject starts by emptying it.
# Nothing is rolled back; nothing needs to be.
def empty_database
  Follow.delete_all
  Post.delete_all
  User.delete_all
end

# A browser for the application, with its cookies, signed in as the user
# of that handle when one is given. Its requests return a
# Rack::MockResponse, with a status, a body and a location.
def browser(as: nil)
  visitor = Rack::Test::Session.new(Rails.application)
  visitor.post("/session", handle: as) if as
  visitor
end

ここでは4つのことが起こります。

2つのメソッドはトップレベルで定義されているので、サブジェクトブロックからはKernelと同じように見えます。このように定義した名前は、もうletの名前には使えません。

モデル

投稿には本文があり、本文は空であってはならず、280文字を超えてもなりません。仕様spec/models/post_spec.rbは、本文をパラメーターとし、レコードのメソッドvalid?、errors、mentionsでそれを述べます。

# frozen_string_literal: true

require "fix"

# A post, built from a body: it mentions the handles of the body, and
# says why an empty or an overlong body is refused.
Fix :Post do
  let(:body) { "Good morning, @bob and @carol." }

  on :valid? do
    it MUST be_true
  end

  on :mentions do
    it MUST eq %w[bob carol]
  end

  with body: "" do
    on :valid? do
      it MUST be_false
    end

    on :errors do
      on :full_messages do
        it MUST eq ["Body can't be blank"]
      end
    end
  end

  with body: "a" * 281 do
    on :valid? do
      it MUST be_false
    end

    on :errors do
      on :full_messages do
        it MUST eq ["Body is too long (maximum is 280 characters)"]
      end
    end
  end
end

テストfix/models/post_fix.rbは、その本文をもつユーザーの投稿を作り、errorsが埋まるように検証します。

#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative "../support/rails"
require_relative "../../spec/models/post_spec"

# The subject is a new post of Alice with the body, a parameter of the
# specification, validated.
exit(Fix[:Post].test do
  empty_database
  User.create!(handle: "alice").posts.new(body:).tap(&:validate)
end)

ユーザーは期待ごとに、空にしたばかりのデータベースの中で、ブロックの中で作られます。テストに必要なレコードはサブジェクトのあるところで作り、親プロセスで一度だけ実行されるファイルの中では決して作りません。すでに存在する行、たとえば使用済みのハンドルやフォロー済みのユーザーが必要なテストも、そこで作ります。

コントローラー

コントローラーのテストのサブジェクトはレスポンスです。仕様spec/controllers/posts_spec.rbは、サインインした訪問者とそうでない訪問者について、そのステータス、ロケーション、本文を判定します。

# frozen_string_literal: true

require "fix"

# The response to posting the body, for the visitor signed in with the
# handle: home when the post is saved, the form again with the reason
# when it is not, the sign-in page for a visitor who is not signed in.
Fix :CreatePost do
  let(:handle) { "alice" }
  let(:body) { "Hello, world!" }

  on :status do
    it MUST eq 302
  end

  on :location do
    it MUST eq "http://example.org/"
  end

  with body: "a" * 281 do
    on :status do
      it MUST eq 422
    end

    on :body do
      it MUST match(/Body is too long/)
    end
  end

  with handle: nil do
    on :status do
      it MUST eq 302
    end

    on :location do
      it MUST eq "http://example.org/session/new"
    end
  end
end

テストfix/controllers/posts_fix.rbはユーザーを作り、ハンドルでブラウザーをサインインさせ、本文を投稿してレスポンスを与えます。

#!/usr/bin/env ruby
# frozen_string_literal: true

require_relative "../support/rails"
require_relative "../../spec/controllers/posts_spec"

# The subject is the response to posting the body, for the visitor
# signed in with the handle; both are parameters of the specification.
exit(Fix[:CreatePost].test do
  empty_database
  User.create!(handle: "alice")
  browser(as: handle).post("/posts", post: { body: })
end)

Rack::Testのリクエストのホストはexample.orgで、ロケーションはそのためです。サインインは訪問者が行うのと同じリクエストです。このアプリケーションではパスワードなしでハンドルだけで足りますが、パスワードのあるアプリケーションも、サインインフォームが送るリクエストで同じようにブラウザーをサインインさせます。Railsが生成するconfig/environments/test.rbのとおり、テスト環境ではCSRF対策は無効で、show_exceptionsは:rescuableです。そのため、見つからないレコードは例外ではなく、判定できる404になります。

実行

bin/rails db:prepare
bundle exec fix

db:prepareが開発用とテスト用のデータベースを作ります。続いてfixがfixのファイルを、それぞれ専用のプロセスで実行します。プロセスごとにアプリケーションが一度起動し、実行時間の大半はそこにかかります。各行はspecの期待を指し、すべてのファイルが満たされれば終了ステータスは0です。Rakefileのタスクtask(:fix) { sh "fix" }を使えばrakeで実行できます。アプリケーションの継続的インテグレーションはbin/rails db:prepare、続いてbundle exec fixを実行します。その環境ではCIが設定されているので、Railsの推奨どおり、アプリケーションはeager loadされます。

fixのファイルは実行可能で、1行目に#!/usr/bin/env rubyがあります。たとえばfix/models/post_fix.rbは単独でも動き、config/boot.rbを通してgemを見つけます。

プロセスが隔離しないもの

プロジェクトで使うでは、子プロセスが残していくものを挙げました。Railsアプリケーションでは、それはデータベース(そのためのempty_database)と、子プロセスが親と同じように書き込むログlog/test.logです。プロセスの中にとどまるものはプロセスとともに消えます。たとえばRailsのテスト環境が送信する代わりにActionMailer::Base.deliveriesに保持するメールは、それを送ったプロセスの中、つまりサブジェクトブロックの中で読み、仕様に与えます。

デバッガーでサブジェクトの中で止めるには、プロジェクトで使うにあるとおり、そのコンテキストをプロセス自身の中で実行します(test(fork: false))。それでも各サブジェクトは、まずデータベースを空にします。