2

私はrspec、レール、ルビーにとても慣れていません。私は現在それらを学んでいます。実行する個々のテストごとに get または post 要求を入れていることに気づきましたが、これはあまり DRY ではありません。テストが機能するために、これらのリクエストを発行し続ける必要がありますか? または私は何か基本的なものを欠いていますか?

編集:

実行中のテストごとに、コントローラがリクエストを実行できるように get :page style リクエストを発行する必要があります。しかし、同じアクションのさまざまな側面をテストするときは、同じリクエストを繰り返し発行するため、コードを繰り返します。これは DRY ではありません (同じことを繰り返さないでください)。

describe "Find Movies With Same Director" do
    it "should respond, and find the requested movie" do
      stubFind()
      id = "1"
      get :match_director, :id=>id
      response.code.should eq("200")
    end

    it "should search for movies with the same director" do
      id = "1"
      Movie.should_receive(:match_director).with(id)
      get :match_director, :id=>id
    end

    it "should pass all matching movies to view" do
      id = "1"
      Movie.should_receive(:match_director).with(id).and_return("")
      get :match_director, :id=>id
      assigns[:movies].should not_be nil
    end

    it "should pass a list of movies" do
      id = "1"
      Movie.stub(:match_director).and_return(stub_model(Movie))
      get :match_director, :id=>id

      assigns[:movies].should be_instance_of(Movie)
    end

  end
4

1 に答える 1

3

複数のテストで同じことを行っている場合は、それらを before ブロックに移動できます。

describe 'something' do
    it 'should do one thing' do
        common_thing
        specific_thing
    end

    it 'should do one thing' do
        common_thing
        specific_thing
    end
end

になる

describe 'something' do
    before :each do
        common_thing
    end

    it 'should do one thing' do
        specific_thing
    end

    it 'should do one thing' do
        specific_thing
    end
end

すべてのテストで共通のものを 1 回だけ呼び出したい場合は、 に置き換えbefore :eachますbefore :all

get :match_director, :id=>id編集:編集を見た後、呼び出しをメソッドに入れて代わりに使用できると思います:

def call_match_director
    get :match_director, :id=>id
end

そうすれば、パラメーターを 1 か所で呼び出しに簡単に追加できます。let コンストラクトを使用して id を変数に入れることもできます。

let(:id) { "1" }

全体として、次のようになります。

describe "Find Movies With Same Director" do
  let(:id) { "1" }

  def call_match_director
    get :match_director, :id=>id
  end

  it "should respond, and find the requested movie" do
    stubFind()
    call_match_director
    response.code.should eq("200")
  end

  it "should search for movies with the same director" do
    Movie.should_receive(:match_director).with(id)
    call_match_director
  end

  it "should pass all matching movies to view" do
    Movie.should_receive(:match_director).with(id).and_return("")
    call_match_director
    assigns[:movies].should not_be nil
  end

  it "should pass a list of movies" do
    Movie.stub(:match_director).and_return(stub_model(Movie))
    call_match_director
    assigns[:movies].should be_instance_of(Movie)
  end
end
于 2012-10-27T21:04:46.503 に答える