在rspec共享示例中传递参数

时间:2019-02-19 00:38:22

标签: ruby rspec

我对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]始终以“”传递

我不确定我在这里想念什么。

1 个答案:

答案 0 :(得分:0)

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

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(如果需要,则使用夹具)来清理很多变量作业。