简体   繁体   English

我应该如何使用rspec rails测试此代码?

[英]How should I test this code with rspec rails?

In my rails application I have a module with an API call that I would like to write rspec tests for. 在我的rails应用程序中,我有一个带有API调用的模块,我想为其编写rspec测试。 What would you write as proper tests for this? 你会写什么作为适当的测试? I have read not to combine httparty with rspec because it is very slow and now I have no idea how to do this. 我已经读过不要将httparty与rspec结合使用,因为它非常慢,现在我不知道如何做到这一点。 Thanks for the advice! 谢谢你的建议!

module BandsInTown
  class API
    attr_reader :artist_name, :info, :events

    def initialize(artist_name)
        @artist_name = artist_name
    end

    def artist_info
        @info = fetch_data
    end

    def artist_events
        @events = fetch_data 'events'
    end

    private

    def fetch_data(endpoint = nil)
        request_url = "http://api.bandsintown.com/artists/#{[@artist_name, endpoint].compact.join('/')}.json?api_version=2.0&app_id=AUTH_KEY"
        resp = HTTParty.get(request_url)
        return false if resp.code != 200
        resp
    end
  end
end

I would use webmock to get around making API requests. 我会使用webmock来绕过发出API请求。

Here's an example on how the code in yout spec_helper.rb could look like: 这是一个关于你的spec_helper.rb代码如何看起来的例子:

require 'webmock/rspec'

def stub_api_requests
  response = File.read('spec/fixtures/payload.json')
  stub_request(:get, %r{http:\/\/api.bandsintown.com\/artists/\/(.)*})
    .to_return(
      status: 200,
      body: response
    )
end

config.before(:each) do
  stub_api_requests
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM