Ruby on rails 如何在不使用eval方法的情况下,使用RSpec和参数化代码进行共享示例测试?
我在RSpec中有一个共享的示例,它测试SMS发送。在我的应用程序中,我有几个发送短信的方法,所以我想对我测试的代码进行参数化,这样我就可以对我的所有方法使用我的共享示例。我发现的唯一方法是使用Ruby on rails 如何在不使用eval方法的情况下,使用RSpec和参数化代码进行共享示例测试?,ruby-on-rails,rspec,dry,Ruby On Rails,Rspec,Dry,我在RSpec中有一个共享的示例,它测试SMS发送。在我的应用程序中,我有几个发送短信的方法,所以我想对我测试的代码进行参数化,这样我就可以对我的所有方法使用我的共享示例。我发现的唯一方法是使用eval函数: RSpec.shared_examples "sending an sms" do |action_code| it "sends an sms" do eval(action_code) expect(WebMock).to have_requested(**my_r
eval
函数:
RSpec.shared_examples "sending an sms" do |action_code|
it "sends an sms" do
eval(action_code)
expect(WebMock).to have_requested(**my_request**).with(**my_body**)
end
end
所以我可以这样使用这个例子:
it_behaves_like "sending an sms",
"post :accept, params: { id: reservation.id }"
it_behaves_like "sending an sms",
"post :create, params: reservation_attributes"
如何在不使用eval
功能的情况下实现这一点?我尝试使用yield
命令的模式,但由于范围限制,该模式不起作用:
失败/错误:post:create,params:reservation\u属性
reservation\u属性
在示例组中不可用(例如描述
或上下文
块)。它只能从单个示例(例如It
块)或在示例范围内运行的构造(例如before
,let
等)中获得
实际上,在您的情况下,action和params可以作为参数传递到共享示例中:
RSpec.shared_examples "sending an sms" do |action, params|
it "sends an sms" do
post action, params: params
expect(WebMock).to have_requested(**my_request**).with(**my_body**)
end
end
并称为:
it_behaves_like "sending an sms", :accept, { id: reservation.id }
it_behaves_like "sending an sms", :create, reservation_attributes
或者你可以定义
重要警告:我们不应该使用
let这里的代码>函数(带感叹号),因为这样我们的大括号中的代码会在整个测试之前执行,也会在块之前执行,这可能会非常令人不安。我只是习惯性地在函数中添加感叹号,这不是个好主意。
RSpec.shared_examples "sending an sms" do
it "sends an sms" do
action
expect(WebMock).to have_requested(**my_request**).with(**my_body**)
end
end
it_behaves_like "sending an sms" do
let(:action) { post :accept, params: { id: reservation.id } }
end
it_behaves_like "sending an sms" do
let(:action) { post :create, params: reservation_attributes }
end