繁体   English   中英

在Rails中使用rspec模拟/存根控制器Recaptcha方法

[英]mocking/stubbing a controller recaptcha method with rspec in rails

我只是在学习如何使用存根和模拟,并且我想模拟以下verify_recaptcha方法来测试条件的两种结果。

我的控制器代码(DogMailsController)

      if verify_recaptcha(:model=>@email,:message=>"Verification code is wrong", :attribute=>"verification code")  
        if DogMail.make_mail dog_mail_params
          result = "success"
        else
          result = "fail"
        end
      else
        flash.delete(:recaptcha_error)
        flash.now[:error] = "Validation Failed. Please enter validation numbers/letters correctly at bottom."
        render :action => 'new', :locals => { :@email => DogMail.new(dog_mail_params)}
      end
     end

到目前为止我的规格

context "when master not signed in" do 
  context "when recaptcha verified" do 
    context "with valid params" do 
      it "should save the new dog mail in the database" do  

        expect{
          post :create, dog_mail: attributes_for(:dog_mail)
        }.to change(DogMail, :count).by(1)
      end
    end 
    context "with invalid params" do 
    end
  end

为了存根/模拟出verify_recaptcha,我应该超出预期的是什么? 我尝试了DogMailsController.stub(:verify_recaptcha).and_return(false)但它似乎不起作用。

您只需要存根controller.verify_recaptcha ,所以使用RSpec 3语法:

allow(controller).to receive(:verify_recaptcha).and_return(true)

Recaptcha gem的最新版本(我认为是3.2+默认情况下会将 小部件隐藏在测试中 ,因此与Recaptcha成功相比,您更有可能最终需要模拟Recaptcha故障。 如果您正在直接测试Rails控制器,则可以使用上述infused的答案的变体:

expect(controller).to receive(:verify_recaptcha).and_return(false)

如果您使用的是Rails 5系统或需要规格,则可能需要使用expect_any_instance_of

expect_any_instance_of(MyController).to receive(:verify_recaptcha).and_return(false)

您也可以使用

expect_any_instance_of(Recaptcha::Verify)

请注意,尽管在某些情况下(例如服务器超时), verify_recaptcha将引发Recaptcha::RecaptchaError而不是返回false,因此您可能也想测试一下-如上,但请替换

and_return(false)

and_raise(Recaptcha::RecaptchaError)

(碰巧的是,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM