Rowandish Rowandish - 3 months ago 10
JSON Question

Why does my Cucumber scenario that uses json_spec fail, and where is last_json defined?



It is a very newbie question: I am developing a REST API using Rails and I'd like to use json_spec to handle JSON in RSpec and Cucumber.
I created my feature test (from here):

Feature: User API
Scenario: User list
Given I post to "/users.json" with:
"""
{
"first_name": "Steve",
"last_name": "Richert"
}
"""
And I keep the JSON response at "id" as "USER_ID"
When I get "/users.json"
Then the JSON response should have 1 user
And the JSON response at "0" should be:
"""
{
"id": %{USER_ID},
"first_name": "Steve",
"last_name": "Richert"
}
"""


But I got this error:

Given(/^I post to "(.*?)" with:$/) do |arg1, string|
pending # express the regexp above with the code you wish you had
end

When(/^I get "(.*?)"$/) do |arg1|
pending # express the regexp above with the code you wish you had
end


I think methods get and post are provided by capybara, but I cannot make the system recognize them.

I also read that I’ll need to define a last_json method but I don't know where I should add it.

Thanks!

Answer

As the blog post you cited says, you need to write the "I post" and "I get" steps.

The get and post methods available in Cucumber steps are provided by rack-test, which Capybara depends on. Capybara is not designed to POST programmatically, so I would write those steps using the rack-test methods:

When /^I get "(.*?)"$/ do |path|
  get path
end

Given /^I post to "(.*?)" with:$/ do |path, body|
  post path, body
end

Define last_json in env.rb, or in another .rb file in features/support. If you use rack-test, last_json will need to use rack-test too:

def last_json
  last_response.body`enter code here`
end