我对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和电子邮件将正确传递。但是,优惠券[0]和优惠券[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(或固定装置(如果是您的喜好))来清理大量变量作业。