Rspec-hooks

提供:Dev Guides
移動先:案内検索

RSpec-フック

単体テストを作成する場合、テストの前後にセットアップコードとティアダウンコードを実行すると便利なことがよくあります。 セットアップコードは、テストの条件を構成または「セットアップ」するコードです。 分解コードはクリーンアップを行い、後続のテストで環境が一貫した状態になるようにします。

一般的に、テストは互いに独立している必要があります。 テストのスイート全体を実行し、そのうちの1つが失敗した場合、テスト中のコードにバグがあり、前のテストが環境を一貫性のない状態にしたためではなく、失敗したことを確信する必要があります。

RSpecで使用される最も一般的なフックは、フックの前後です。 これらは、上記で説明したセットアップおよび分解コードを定義および実行する方法を提供します。 このサンプルコードを考えてみましょう-

class SimpleClass
   attr_accessor :message

   def initialize()
      puts "\nCreating a new instance of the SimpleClass class"
      @message = 'howdy'
   end

   def update_message(new_message)
      @message = new_message
   end
end

describe SimpleClass do
   before(:each) do
      @simple_class = SimpleClass.new
   end

   it 'should have an initial message' do
      expect(@simple_class).to_not be_nil
      @simple_class.message = 'Something else. . .'
   end

   it 'should be able to change its message' do
      @simple_class.update_message('a new message')
      expect(@simple_class.message).to_not be 'howdy'
   end
end

このコードを実行すると、次の出力が得られます-

Creating a new instance of the SimpleClass class
.
Creating a new instance of the SimpleClass class
.
Finished in 0.003 seconds (files took 0.11401 seconds to load)
2 examples, 0 failures

何が起こっているかを詳しく見てみましょう。 before(:each)メソッドは、セットアップコードを定義する場所です。 :each引数を渡すと、サンプルメソッドグループの各サンプルの前にbeforeメソッドを実行するように指示しています。 上記のコードの記述ブロック内の2つのitブロック。

@simple_class = SimpleClass.newという行では、SimpleClassクラスの新しいインスタンスを作成し、それをオブジェクトのインスタンス変数に割り当てています。 あなたが疑問に思うかもしれないオブジェクトは何ですか? RSpecは、describeブロックのスコープ内でバックグラウンドで特別なクラスを作成します。 これにより、このクラスのインスタンス変数に値を割り当てることができ、例のitブロック内でアクセスできます。 これにより、テストでよりクリーンなコードを簡単に記述できます。 各テスト(例)にSimpleClassのインスタンスが必要な場合、そのコードをbeforeフックに入れることができ、各例に追加する必要はありません。

「Creating a new instance of the SimpleClass class」という行がコンソールに2回書き込まれていることに注意してください。これは、各* itブロック*でフックが呼び出される前を示しています。

前述したように、RSpecにはafterフックもあり、beforeフックとafterフックの両方が引数として使用できます。 afterフックは、指定されたターゲットの後に実行されます。 すべてのターゲットは、すべての例の前/後にフックが実行されることを意味します。 各フックがいつ呼び出されるかを示す簡単な例を次に示します。

describe "Before and after hooks" do
   before(:each) do
      puts "Runs before each Example"
   end

   after(:each) do
      puts "Runs after each Example"
   end

   before(:all) do
      puts "Runs before all Examples"
   end

   after(:all) do
      puts "Runs after all Examples"
   end

   it 'is the first Example in this spec file' do
      puts 'Running the first Example'
   end

   it 'is the second Example in this spec file' do
      puts 'Running the second Example'
   end
end

上記のコードを実行すると、この出力が表示されます-

Runs before all Examples
Runs before each Example
Running the first Example
Runs after each Example
.Runs before each Example
Running the second Example
Runs after each Example
.Runs after all Examples