How to use Cucumber to test non-Ruby, non-Rack API

2019-05-22 14:06发布

问题:

I use cucumber for lots of things. I really like it as a BDD environment.

So I'd like to use it as an external tool to test an API. I'd like to do things like:

  Scenario: Hit api /info path and get info back
    When I visit the API path '/info'
    Then I should see the following text "Here's info on the API"

or something similar. I mainly want to treat the API as a black box and test only inputs and outputs. I don't plan on inspecting anything inside the API.

Most of the libraries I've looked at that work with Cucumber (for example Capybara) seem to be designed around Rack-based applications. I'd like something similar to that but with no dependency on Rack.

What gems, if any, exist that have no rack dependencies. Or is there a way to use Capybara to test an API that's on a remote server?

回答1:

I wouldn't use Capybara to test a remote API because Capybara is made for testing applications is used for testing applications with a HTML UI (as Aslak points out in the comments).

Instead, I would use Cucumber* in conjunction with something like HTTParty which would be the tool used to make the HTTP requests and parse them neatly. Here's an idea:

When /^I visit the API path '(.*?)'/ do |path|
  @result = HTTParty.get("http://theapi.com/#{path}")
end

Then /^I should see the following result:$/ do |result|
  @result.should == result
end

The final step here you would use like this:

Then I should see the following result:
   """
     { success: true }
   """

* I would actually use RSpec personally, I find the syntax less clumsy.



回答2:

I've been using cucumber against a Drupal application for some time now. It's working out well.

This helped me set up capybara with selenium

https://github.com/thuss/standalone-cucumber

If you want to use mechanize, it's a bit buggy. I had to use 0.3.0-rc3 as there were some issues following redirects etc. There are still a few issues with submitting forms with field names containing "[]" characters. I can't quite remember as another person on my team discovered that bug.