15 May 2014, 14:01
Generic-user-small

Chris Davies (1 post)

I have attempted to complete the Try This exercise ‘Add a scenario that starts with one fruit in the datbase, adds another one via an HTTP POST, and then verifies that you now have two fruit.’

I have created the step to do the post:

When the client requests POST /addFruit with the following:
    | name       | color |
    | strawberry | red   |

And wired it up like this:

When /^the client requests POST (.*) with the following:$/ do |path, body|
  @last_response = HTTParty.post('http://localhost:9999' + path, :body => body.hashes.to_json)
end

In the fruit_app.rb the post is dealt with like so:

post '/addFruit' do
    File.open('fruits.json', "w") do |f|
      f.write(params[:body])
    end
  end

The problem is that when I run the scenario ‘nil’ is being written to fruits.json file. I have changed the code to get it to write “Hello world” but it still writes ‘nil’ to the file. What am I doing wrong here? Please bear in mind I am very new to ruby…

09 Jun 2014, 11:52
Avatar_pragsmall

Matt Wynne (87 posts)

Hi Chris,

Are you still stuck on this problem? Your code looks OK to me.

Try putting in a debug statement in the post request handler to print out the whole params hash. My guess is that maybe you need to access the body using a string key rather than a symbol, like params['body'] but printing out the whole params hash should confirm that.

You can just add a like like puts params.inspect or the shorthand p params to print it out to the console.

  You must be logged in to comment