在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调用。

我的申请代码是……

  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时期的新手。

谢谢

使用模拟作为响应,您可以执行此操作。 我对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 

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

最受欢迎的两个是WebMock和VCR 。