我们能够通过使用“Rest-Client”gem(调用端点)和 Cucumber 挂钩(用于确定何时生成测试数据)来创建自己的测试数据。
请参阅下面的示例,了解我们如何使用 Rest-Client gem、黄瓜钩子、数据管理器类和工厂模块创建新帐户/客户。这是link,其中包含有关其工作原理的更多信息。
AccountDataManager.rb
require 'rest-client'
require_relative '../factory/account'
class AccountDataManager
include Account
def create
current_time = Time.now.to_i
username = 'test_acc_' + current_time.to_s
password = 'password1'
url = 'http://yourURLhere.com/account/new'
request_body = manufacture_account(username, password)
response = RestClient.post url, request_body.to_json, {:content_type => 'application/json', :accept => 'application/json'}
if response.code != 200
fail(msg ="POST failed. Response status code was: '#{response.code}'")
end
response_body = JSON.parse(response
clientId = response_body['Account']['ClientId']
# return a hash of account details
account_details = {
username: username
password: password,
clientId: clientId
}
end
end
Account.rb
下面的工厂制造请求的主体。
module Account
def manufacture_account(username, password)
payload = {
address:{
:Address1 => '2 Main St',
:Address2 => '',
:Suburb => 'Sydney',
:CountryCode => 8
},
personal:{
:Title => 'Mr',
:Firstname => 'John',
:Surname => 'Doe',
:UserName => "#{username}",
:Password => "#{password}",
:Mobile => '0123456789',
:Email => "#{username}@yopmail.com",
:DOB => '1990-12-31 00:00:00'
}
}
end
end
Hook.rb
您应该将您的 hook.rb 文件添加到一个共享目录,然后将其引用添加到您的 env.rb 文件中(我们将我们的挂钩文件添加到“/features/support”目录)。
require_relative '../data_manager/data_manager_account'
Before() do
$first_time_setup ||= false
unless $first_time_setup
$first_time_setup = true
# call the data managers needed to create test data before
# any of your calabash scenarios start
end
end
Before('@login') do
# declare global variable that can be accessed by step_definition files
$account_details = AccountDataManager.new.create
end
at_exit do
# call the data managers to clean up test data
end
Login_steps.rb
拼图的最后一部分是让您的葫芦场景使用您刚刚生成的测试数据。为了解决这个问题,我们在 hook.rb 文件中声明了一个全局变量($account_details),并在我们的 step_definition 文件中引用了它。
Given(/^I log in with newly created customer$/) do
@current_page = @current_page.touch_login_button
unless @current_page.is_a?(LoginPage)
raise "Expected Login page, but found #{@current_page}"
end
# use global variable declared in hook.rb
@current_page = @current_page.login($account_details)
unless @current_page.is_a?(HomePage)
raise "Expected Home page, but found #{@current_page}"
end
end