7

私はこのようなコントローラー仕様を持っています:

describe "#create" do
  before { post 'create', params }
  context "when the artist is valid" do
    before { allow(artist).to receive(:save).and_return(true) }
    it { expect(page).to redirect_to(root_path) }
    it { expect(notifier).to have_received(:notify) }
  end
end

これは単純な仕様ですが、describe の before ブロックが context の before ブロックの前に実行されるため機能しません。artist.saveそのため、 create アクションが呼び出されたときにの結果はスチューブされません。

これをやろうとしました:

describe "first describe" do
  before { puts 2 }
  describe "second describe" do
    before { puts 1 }
    it "simple spec" do
      expect(1).to eq 1
    end
  end
end

「1」の前に「2」が見えます。よくわかりませんが、以前のバージョンで動作していたと思います。

私は知っています、私はこれを行うことができます:

describe "#create" do
  context "when the artist is valid" do
    before { allow(artist).to receive(:save).and_return(true) }
    it "redirect to the root path" do
      post 'create', params
      expect(page).to redirect_to(root_path)
    end

    it "do notifications" do
      post :create, params
      expect(notifier).to have_received(:notify)
    end
  end
end

しかし、私はそれがあまりきれいではないと思います。

このページで、http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Hooks#before-instance_methodを見つけました。注文は次のようにする必要があります。

before(:suite) # declared in RSpec.configure
before(:all)   # declared in RSpec.configure
before(:all)   # declared in a parent group
before(:all)   # declared in the current group
before(:each)  # declared in RSpec.configure
before(:each)  # declared in a parent group
before(:each)  # declared in the current group

この例ではそうではありません。

よくわかりませんが、古いバージョンの rspec で動作していたと思います。

解決策はありますか?

4

1 に答える 1

7

rspec でフックの順序を変更しないことを強くお勧めします。これにより、アプリは非標準になり、Rails は標準に基づいて構築され、期待どおりに機能します。

あなたがそれを「設計どおり」に説明しているものはすべて。外側の before ブロックは、常に内側のブロックの前に呼び出されます。

あなたが「きれいではない」と感じる例は、コントローラーの仕様を行う標準的な方法です。より保守しやすく読みやすいように、この方法で行うことをお勧めします。私にはまったく不潔に見えません。

とはいえ、いくつかのオプションがあります。

  1. メソッドを使用できます。私は何度do_postか、またはそれに類似した方法を持っていました
  2. let遅延初期化されたブロックを使用できます。ブロックが最初に実行される前に他のブロックに依存している場合、それは不自然だと思いますが、それはオプションです。
  3. を定義できますsubjecthttps://www.relishapp.com/rspec/rspec-core/v/2-6/docs/subject/explicit-subject
于 2013-07-22T01:39:01.210 に答える