ruby - RSpec:对类似的 it 块使用 each 循环
问题描述
我正在编写测试以检查某些端点是否返回 200 状态。
RSpec.describe 'API -> ' do
before do
@token = get_token
end
describe 'Status of below end points should be 200 -->' do
it "/one should return a status code of 200" do
get("/api/v1/one", params: {
authentication_token: @token
})
expect(response.status).to eql(200)
end
it "/two should return a status code of 200" do
get("/api/v1/two", params: {
authentication_token: @token
})
expect(response.status).to eql(200)
end
it "/three should return a status code of 200" do
get("/api/v1/three", params: {
authentication_token: @token
})
expect(response.status).to eql(200)
end
end
end
有很多这样的端点,我想知道是否有更有效的方法来写这个,比如
RSpec.describe 'API -> ' do
before do
@token = get_token
@end_points = ['one', 'two', 'three', 'four', 'five']
end
describe 'Status of below end points should be 200 -->' do
@end_points.each do |end_point|
it "/#{end_point} shold returns a status code of 200" do
get("/api/v1/#{end_point}", params: {
authentication_token: @token
})
expect(response.status).to eql(200)
end
end
end
end
但这不起作用并给出错误each called for nil
。
对此的任何帮助都会很棒,谢谢。
解决方案
您可以使用的是共享示例。
shared_examples "returns 200 OK" do |endpoint|
let(:token) { get_token }
it "should return a status code of 200" do
get(endpoint, params: { authentication_token: token })
expect(response.status).to eql(200)
end
end
describe '..' do
include_examples 'returns 200 OK', '/api/endpoint/1'
include_examples 'returns 200 OK', '/api/endpoint/2'
end
推荐阅读
- javascript - 在 asp.net 中的 javascript/jquery 中访问服务器端变量
- ios - 从 2018-10-23T06:01:10.806Z 转换为 10-May-2018 和一个单独的时间字符串
- sql - 如何避免在sql server中选择具有特殊符号的行
- android - 通过 Firebase 中的 JAVA 动态克隆/复制和填充 Layout 中的数据 - Android
- amazon-rds - 自动执行 - 在 rds 参数组中应用更改,重新启动 rds,然后应用另一个更改
- c# - 构建docfx后PlantUml不渲染图表
- swift - Swift 4 - 如何检查眼睛是否闭合
- sql-server - xp_cmdshell 一直在后台运行
- bash - 如何将我的分布式 shell 脚本映射到 ansible
- java - 如何旋转 mp4 文件?