3

SinatraベースのAPI用の一連のRSpecテストがあります。それらをリファクタリングして、少し単純にし、繰り返しを減らしたいと思います。

ルートのテストの例を次に示します。

describe 'post /sections with empty data' do
    before do

        params = {
            :site_id    => site.id,
            :page_id    => page.id,
        }

        post '/sections', params, @session
    end

    specify { last_response.status.should == 200 }
    specify { json_response['id'].should_not be_nil }
    specify { json_response['type'].should == default_section_type }
end

各テストは同じベースURLを使用し、同じセッションデータを使用します。唯一の違いは、パラメーターと応答の内容です。ルートごとに少なくとも4つのテスト(GET、POST、PUT、DELETE)があり、通常はそれ以上です。

これらのテストをより管理しやすくする方法はありますか?

4

2 に答える 2

3

metaprogramimngに頼らずに、ネストされたdescribeブロックを使用して、必要なパラメーターのみをオーバーライドできます。

describe "/sessions" do
  before do
    send(http_method, "/sessions", params, @session)
  end

  describe "with POST" do
    let(:http_method) { :post }

    describe "and empty data" do
      let(:params) do
        { :site_id => site.id, :page_id => page.id }
      end

      specify { last_response.status.should == 200 }
      specify { json_response['id'].should_not be_nil }
      specify { json_response['type'].should == default_section_type }
    end

    describe "with non-empty data" do
      let(:params) do
        # relevant params
      end
    end
  end

  describe "with GET" do
    let(:http_method) { :get }

    # ...
  end
end
于 2012-10-03T23:03:48.643 に答える
1

これが機能するかどうかはわかりませんが、何ができるかはわかります。

describe ' /sections with empty data' do
    before(:all) do
      @params = {
            :site_id    => site.id,
            :page_id    => page.id,
        }
    end

    after(:each) do
      specify { last_response.status.should == 200 }
      specify { json_response['id'].should_not be_nil }
      specify { json_response['type'].should == default_section_type }
    end

    [:get, :post, :put, :delete].each do |http_method|
        it "works with #{http_method}" do
            send(http_method) '/sections', @params, @session
        end
    end
end

アップデート

あなたの質問をもう一度読んで、これはあなたが実際に求めていたものではないことに気づきました。まったく役に立たない場合は教えてください。削除します。

于 2012-10-03T23:06:44.473 に答える