简体   繁体   中英

Ruby Cucumber multi-line quotes with interpolation?

I'm using Cucumber to send in JSON to some API actions. In one instance, I need to know the ID of an object that was built prior to the API call and pass that ID in.

I want to do this:

  Scenario: Creating a print from an existing document
    Given I am logged in as "foo@localhost.localdomain"
      And I have already built a document
     When I POST /api/prints with data:
       """
       {
         "documentId":"#{@document.id}",
         "foo":"bar",
         "etc":"etc" 
       }
       """
     Then check things

Which doesn't work, because the """ string doesn't interpolate variables like a double-quoted string would. The I have already built a document step builds the @document object, so I don't know ahead of time what my ID will be. If it matters, I'm using MongoDB with mongoid, and my efforts to manually set an ID have proven fruitless.

Is there a clean way to accomplish this?

Environment:

ruby: 1.8.7
rails: 3.0.1
cucumber: 0.9.4
cucumber-rails: 0.3.2

Change to ERB syntax ( <%= ... %> ), and then in your step definition, run the string through ERB:

require 'erb'

When %r{^I POST (.+) with data:$} do |path, data_str|
  data = ERB.new(data_str).result(binding)
  # ...
end

ERB is one way to defer evaluation, but perhaps, Theo, this is a little cleaner ?

The two halves of this are the scenario side:

Scenario: Creating a print from an existing document
  Given I am logged in as "foo@localhost.localdomain"
    And I have already built a document
  When I POST /api/prints with data:
   # outer, single quotes defer evaluation of #{@document}
   '{
     "documentId":"#{@document.id}",
     "foo":"bar",
     "etc":"etc" 
   }'
 Then check things

And the step definition side:

When %r{^I POST (.+) with data:$} do |path, data_str|
  # assuming @document is in scope...
  data = eval(data_str)
  # ...
end

I would recommend using scenario outlines and examples using something like

Scenario Outline: Posting stuff
....
When I POST /api/prints with data:
   """
   {
     "documentId": <document_id>,
     "foo":"bar",
     "etc":"etc" 
   }
   """
Then check things

Examples: Valid document
| document_id |
| 1234566     |

Examples: Invalid document
| document_id |
| 6666666     |

in examples. That would make it clear where the values came from at least. Check Substitution in Scenario Outlines here http://cukes.info/step-definitions.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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