在RSpec中记录RestClient响应

问题描述 投票:10回答:3

我有以下规格......

  describe "successful POST on /user/create" do
    it "should redirect to dashboard" do
      post '/user/create', {
          :name => "dave",
          :email => "[email protected]",
          :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做到这一点吗?我已经用Google搜索并发现了许多博客文章,这些文章从表面上划过,但我实际上找不到答案。我对RSpec时期很新。

谢谢

ruby rspec sinatra rest-client
3个回答
17
投票

使用mock进行响应,您可以执行此操作。我对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 => "[email protected]",
      :password => "another_pass"
    }
    last_response.should be_redirect
    follow_redirect!
    last_request.url.should == 'http://example.org/dave/dashboard'
  end
end

3
投票

我会考虑使用gem来完成这样的任务。

其中两个最受欢迎的是WebMockVCR


0
投票

Instance doubles是要走的路。如果存根不存在的方法,则会出现错误,这会阻止您在生产代码中调用不存在的方法。

      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)
© www.soinside.com 2019 - 2024. All rights reserved.