【发布时间】: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示例共享它们的结果并不典型。 -
尽量减少例子。如果您认为传递参数不起作用,请编写一个仅传递参数的简单示例。看起来你用对了,但是传递了空字符串