代码之家  ›  专栏  ›  技术社区  ›  Karol Selak

如何在不使用eval方法的情况下,使用参数化代码与RSpec进行共享示例测试?

  •  3
  • Karol Selak  · 技术社区  · 8 年前

    我在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_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"
    

    如果不使用 评估 作用我试着用这个模式 yield 命令,但由于作用域的原因,该命令不起作用:

    失败/错误:post:创建,参数:reservation\u属性 reservation_attributes 在示例组(例如a)上不可用 describe 或 context 块)。它仅在单个示例中可用(例如。 it 块)或在示例范围内运行的构造(例如。 before ,则, let 等)。

    1 回复  |  直到 8 年前
        1
  •  4
  •   Igor Drozdov    8 年前

    实际上,在您的情况下,可以将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
    

    或者您可以定义 separate action for every block

    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