3

I am running into this situation (similar to this) when trying to do the following:

Scenario: Create User
Given path 'user'
    And request read('user.json');
    When method post
    Then status 200
    And def user_id = response.userId

Scenario: Test A
   Given path 'user/' + user_id <- Received javascript error here
   ...

Scenario: Test B
   Given path 'user/' + user_id <- Received javascript error here
   ...

Scenario: Test A
   Given path 'user/' + user_id <- Received javascript error here
   ...

Basically what i am trying to do is create a user in my database first, then run it through a series of test and use a last scenario to delete this user. Therefore, i need to share the user_id value across multiple scenarios. Background doesn't work for me because that means i have to create a new user for each scenario. I have seen in the demo that a simple way would be to put all test under 1 scenario but i don't feel that it is right to put all tests on 1 scenario

I have reviewed the karate demo but i did not come across any sample code that will help my situation. May i know the right way to do this in Karate? Thanks.

zeus1234
  • 453
  • 1
  • 5
  • 15

1 Answers1

2

I think you are missing the callonce keyword. Understand it and then look at the demos, for example, this one: callonce.feature.

You will need to move the 'common' code into a separate feature, but that is the right thing to do, because you will typically want it re-usable by multiple feature files as well.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Is callonce the only get to share value across scenario within a feature file? Is there any other ways? I tried setting and getting value using js function via the karate object but when retrieving in the new scenario, the set value is not there anymore. – zeus1234 Dec 04 '17 at 09:41
  • @david use `callonce` **AND** in a `Background` section. kindly read the doc and example I provided carefully ! all the best. – Peter Thomas Dec 04 '17 at 09:55
  • Hi Peter, I forgot to add in my earlier reply that i did read the documentations and tried the backgroud+callonce method using the demo app as a guide. It work well for me. Basically i created a AddUser.feature file that added 1 user and passed me back the id to test with the rest of the scenarios. However, i am wondering if it is possible to contain test setup and teardown code together with the scenarios within the feature file itself, rather than having to write them in a separate file and passing the value back? Maybe i am not thinking about something rightly? – zeus1234 Dec 04 '17 at 15:13
  • @david No. I clearly mentioned this in my main answer. If you find writing a separate feature file troublesome, then I can't help you :P – Peter Thomas Dec 04 '17 at 15:18
  • @david I think you are new here. do you mind up-voting and marking the answer as "accepted" it helps maintain the quality of answers on Stack Overflow. thanks. – Peter Thomas Dec 05 '17 at 02:59