在 RSpec 中存根 RestClient 响应 [英] Stubbing RestClient response in RSpec

查看:44
本文介绍了在 RSpec 中存根 RestClient 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下规格...

  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 调用.

The post method on the Sinatra application makes a call to an external service using rest-client. I need to somehow stub the rest client call to send back canned responses so I don't have to invoke an actual HTTP call.

我的应用程序代码是...

My application code is...

  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 时期很陌生.

Can someone tell me how I do this with RSpec? I've Googled around and come across many blog posts which scratch the surface but I can't actually find the answer. I'm pretty new to RSpec period.

谢谢

推荐答案

使用 mock 对于回复,您可以这样做.总的来说,我对 rspec 和测试还是很陌生,但这对我有用.

Using a mock for the response you can do this. I'm still pretty new to rspec and test in general, but this worked for me.

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

这篇关于在 RSpec 中存根 RestClient 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆