12

私は次の仕様を持っています...

  describe "successful POST on /user/create" do
    it "should redirect to dashboard" do
      post '/user/create', {
          :name => "dave",
          :email => "dave@dave.com",
          :password => "another_pass"
      }
      last_response.should be_redirect
      follow_redirect!
      last_request.url.should == 'http://example.org/dave/dashboard'
    end
  end

Sinatraアプリケーションのpostメソッドは、rest-clientを使用して外部サービスを呼び出します。既定の応答を返送するために、残りのクライアント呼び出しをなんとかしてスタブする必要があるため、実際のHTTP呼び出しを呼び出す必要はありません。

私のアプリケーションコードは...

  post '/user/create' do
    user_name = params[:name]
    response = RestClient.post('http://localhost:1885/api/users/', params.to_json, :content_type => :json, :accept => :json)
    if response.code == 200
      redirect to "/#{user_name}/dashboard"
    else
      raise response.to_s
    end
  end

誰かがRSpecでこれを行う方法を教えてもらえますか?私はグーグルで検索して、表面を傷つけている多くのブログ投稿に出くわしましたが、実際には答えを見つけることができません。私はRSpec期間にかなり慣れていません。

ありがとう

4

3 に答える 3

18

応答にモックを使用すると、これを行うことができます。私はまだrspecとテスト全般にかなり慣れていませんが、これは私にとってはうまくいきました。

describe "successful POST on /user/create" do
  it "should redirect to dashboard" do
    RestClient = double
    response = double
    response.stub(:code) { 200 }
    RestClient.stub(:post) { response }

    post '/user/create', {
      :name => "dave",
      :email => "dave@dave.com",
      :password => "another_pass"
    }
    last_response.should be_redirect
    follow_redirect!
    last_request.url.should == 'http://example.org/dave/dashboard'
  end
end
于 2013-01-10T22:17:42.327 に答える
6

インスタンスダブルは行く方法です。存在しないメソッドをスタブするとエラーが発生し、本番コードに存在しないメソッドを呼び出すことができなくなります。

      response = instance_double(RestClient::Response,
                                 body: {
                                   'isAvailable' => true,
                                   'imageAvailable' => false,
                                 }.to_json)
      # or :get, :post, :etc
      allow(RestClient::Request).to receive(:execute).and_return(response)
于 2019-04-11T01:58:31.000 に答える
3

このようなタスクにはgemを使用することを検討します。

最も人気のある2つは、WebMockVCRです。

于 2013-01-10T22:26:18.377 に答える