在 RSpec 中如何模拟 RestClient 的响应

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调用外部服务。我需要以某种方式存根rest客户端调用,以发送预定义响应,这样我就不必调用实际的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 还比较新手。

谢谢。

3个回答

18

通过使用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 => "dave@dave.com",
      :password => "another_pass"
    }
    last_response.should be_redirect
    follow_redirect!
    last_request.url.should == 'http://example.org/dave/dashboard'
  end
end

1
我建议将 double 设置移到 let 块中,将 post 移到 before 块中。 - ian
谢谢您的建议@iain,但与问题完全无关 :) 但是,它应该有一个describe 'POST on /user/create'块,其中包含let(:sucessful_response) {...}和before块,然后是成功和错误响应的描述。 - Ismael
谢谢大家。我宁愿使用我已经拥有的工具而不是求助第三方,这个方案很好用。 - RobA2345

7

实例双倍是正确的方法。如果您存根不存在的方法,则会出现错误,这会防止您在生产代码中调用不存在的方法。

      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)

3
我会考虑使用一个gem来完成这样的任务。 其中两个最受欢迎的是WebMockVCR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接