【问题标题】:passing arguments in rspec shared example在 rspec 共享示例中传递参数
【发布时间】:2019-04-22 20:28:18
【问题描述】:

我对 Rspec 有点陌生。

这是我的问题

我有一个可以分享的例子

共享示例

RSpec.shared_examples "coupons_shared" do |arg1,email,coupon1,coupon2|
  it "present_coupons" do
    post_rest_url = "https://blahblahblah=" + "#{arg1}" + "&email=" + "#{email}"
    json_request = <<END_OF_MESSAGE
    [
"#{coupon1}",
"#{coupon2}"
    ]
END_OF_MESSAGE
    header = {:accept => "application/json",:content_type => "application/json"}
    resp = RestClient.post(post_rest_url, json_request, header)
    json_obj = JSON.parse(resp)
    expect(json_obj[0]["ccode"]).to include("#{coupon1}")
    expect(json_obj[0]["ccode"]).to include("#{coupon2}")
  end
end

共享示例文件位置在 \spec\support\shared_examples

在实际的规范文件中,我有一个获取优惠券的示例,然后需要使用共享示例进行演示

describe "enrol_cust" do
  cust_id = '1'
  coupons = []
  header_basic_auth = {:accept => "application/json",:content_type => "application/json"}
  random_no = (rand(999) + 10)
  random_no = random_no.to_s
  email = "johndoe" + "#{random_no}" + "@gmail.com"
  st = 1111
  st = st.to_i
  before(:each) do
    @dob = 20.years.ago(Date.today).strftime("%m-%d-%Y")
  end

  it "enrol_cust" do
    post_rest_url = "https://blahblah?st=" + "#{st}"
    json_request = <<END_OF_MESSAGE
{
"email": "#{email}",
"first_name": "John",
"last_name": "Doe",
"date_of_birth": "#{@dob}",
}
END_OF_MESSAGE
    header = header_basic_auth
    resp = RestClient.post(post_rest_url, json_request, header)
    json_obj = JSON.parse(resp)
    cust_id = json_obj["cid"]
  end
# above example gets customer id

it "get_list" do
    get_rest_url = "https://blahblah=" + "#{cust_id}" + "&st=" + "#{st}"
    header = header_basic_auth
    resp = RestClient.get(get_rest_url, header)
    json_obj = JSON.parse(resp)
    coupons = json_obj.collect {|x| x["cccode"]}
end
# above example gets coupons
# I have tried printing out the coupons and I can see the correct coupons in this example

include_examples "coupons_shared" ,"#{st}","#{email}","#{coupons[0]}","#{coupons[1]}"

当我尝试传递参数时,st 和 email 被正确传递。但是,coupons[0] 和 coupons[1] 总是作为 ""

传递

我不确定我在这里缺少什么。

【问题讨论】:

  • 我认为如果您将代码移出it "get_list" 块并移入describe 块,它会起作用。基本上每个it 块都有自己的上下文,与其他it 示例共享它们的结果并不典型。
  • 尽量减少例子。如果您认为传递参数不起作用,请编写一个仅传递参数的简单示例。看起来你用对了,但是传递了空字符串

标签: ruby rspec


【解决方案1】:

要将参数传递给共享示例,请将变量包装在示例块中(不要将它们作为示例中的参数列出):

RSpec.shared_examples "coupons_shared" do
  ...code that includes your variables coupon1, coupon2 etc..
end
include_examples "coupons_shared" do
  coupon1 = coupons[0]
  ...and so on (also works with let)...
  let(:coupon1) { coupons[0] }
end

我还强烈建议您将 HTTP 请求存根,这样它们就不会在您每次运行测试时都访问实际的服务器,并考虑使用 FactoryBot(或者如果您愿意,可以使用固定装置)来清理大量变量任务。

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多