在Ruby中传递散列作为参数

  • 本文关键字:参数 Ruby ruby
  • 更新时间 :
  • 英文 :


我正在尝试实现一个模块,该模块包含要在测试中使用的数据。这是我的模块:

身份验证.rb

module Helpers
module Authentication
def sign_in_as
admin = {
mobile_number: "123456789",
password: "123456"
}
end
end
end

该模块在spec_helper文件中调用:

spec_helper.rb

RSpec.configure do |config|
config.include Helpers::Authentication
end

下面的文件是我接收登录凭据的方法:

登录屏幕.rb

def login_as(**hash)
mobile_number_textfield.send_keys(hash[mobile_number])
password_textfield.send_keys(hash[password])
next_button.click()
end

当我从规范文件中的模块调用函数时,不会输入凭据:

login_spec.rb

RSpec.describe('Login') do
before(:all) do
puts "something here"
end
it('should login as founder') do 
@login_screen.login_as(sign_in_as)
end
end

如何将哈希传递到我的登录方法?

访问时需要使用符号作为哈希键:

def login_as(**hash)
mobile_number_textfield.send_keys(hash[:mobile_number])
password_textfield.send_keys(hash[:password])
next_button.click()
end

您的代码可能会在mobile_number_textfield.send_keys(hash[:mobile_number])中引发错误。

您可以执行以下操作之一:

def login_as(mobile_number:, password:)
mobile_number_textfield.send_keys(mobile_number)
password_textfield.send_keys(password)
next_button.click()
end
def login_as(hash)
mobile_number_textfield.send_keys(hash[:mobile_number])
password_textfield.send_keys(hash[:password])
next_button.click()
end
login_as({mobile_number: "02980298098", password: "password"})

我的工作解决方案:

在我的模块中,我创建了一个只有散列的函数:

身份验证.rb

module Helpers
module Authentication
def sign_in_as
{
mobile_number: '123456789',
password: '123456'
}
end
end
end

我的spec_helper保持相同的

spec_helper.rb

require_relative './helpers/authentication'
RSpec.configure do |config|
config.include Helpers::Authentication
end

在我的login_screen文件中,我向要发送哈希值的每一行添加了一个符号:

登录屏幕.rb

def login_as(**hash)
mobile_number_textfield.send_keys(hash[:mobile_number])
password_textfield.send_keys(hash[:password])
next_button.click()
end

在我的login_spec文件中,我刚刚调用了sign_in_as函数(在我的模块中创建(

提示:在spec文件中,您不需要模块,因为spec_helper文件中添加的行config.include Helpers::Authentication实现了这一点。

login_spec.rb

RSpec.describe('Login') do
before(:all) do
puts "something here"
end
it('should login as founder') do 
@login_screen.login_as(sign_in_as)
end
end

最新更新