【问题标题】:Stubbing RestClient response in RSpec在 RSpec 中存根 RestClient 响应
【发布时间】:2012-12-25 09:33:30
【问题描述】:

我有以下规格...

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

谢谢

【问题讨论】:

    标签: ruby rspec sinatra rest-client


    【解决方案1】:

    使用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
    

    【讨论】:

    • 我建议将double 设置移动到let 块中,将post 移动到before 块中`。
    • 感谢@iain 的建议,但与问题完全无关:) 但是,它应该有一个 describe 'POST on /user/create' 块,带有 let(:sucessful_response) {...} 和前块,然后是成功的描述和错误响应。
    • 谢谢大家。我宁愿将此解决方案与我已有的工具一起使用,也不愿求助于第三方,这很有效。
    【解决方案2】:

    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)
    

    【讨论】:

      【解决方案3】:

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

      最受欢迎的两个是WebMockVCR

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-09
        • 2014-02-06
        • 1970-01-01
        • 2014-09-15
        • 1970-01-01
        • 1970-01-01
        • 2014-05-16
        • 1970-01-01
        相关资源
        最近更新 更多