在 rails 中使用 rspec 模拟/存根控制器 recaptcha 方法 [英] mocking/stubbing a controller recaptcha method with rspec in rails
问题描述
我刚刚学习如何使用存根和模拟,我想模拟下面的 verify_recaptcha
方法来测试条件的两种结果.
I'm just learning how to use stubs and mocks and I would like to mock out the below verify_recaptcha
method to test both outcomes of the condition.
我的控制器代码 (DogMailsController)
my controller code (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)
但它似乎不起作用.
What should I put above expect inorder to stub/mock out verify_recaptcha? I tried DogMailsController.stub(:verify_recaptcha).and_return(false)
but it doesn't seem to work.
推荐答案
Recaptcha gem 隐藏小部件默认情况下在测试中,因此您更有可能最终需要模拟 Recaptcha 失败而不是 Recaptcha 成功.如果您要直接测试 Rails 控制器,则可以使用 infused 以上答案的变体:
Recent versions (3.2+ I think) of the Recaptcha gem hide the widget in test by default, so you're more likely to end up needing to mock a Recaptcha failure than a Recaptcha success. If you're testing a Rails controller directly, you can use a variant of infused's answer above:
expect(controller).to receive(:verify_recaptcha).and_return(false)
如果您使用的是 Rails 5 系统或请求规范,则可能需要使用 expect_any_instance_of
:
If you're in a Rails 5 system or request spec, you may need to use 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,因此您可能需要测试对于那些 - 如上所述,但替换
Note though that there are also situations (e.g. a server timeout) in which verify_recaptcha
will raise Recaptcha::RecaptchaError
instead of returning false, so you may want to test for those as well -- as above, but replace
and_return(false)
与
and_raise(Recaptcha::RecaptchaError)
(碰巧,这也会
这篇关于在 rails 中使用 rspec 模拟/存根控制器 recaptcha 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!