[英]mocking/stubbing a controller recaptcha method with rspec in rails
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. 我只是在学习如何使用存根和模拟,并且我想模拟以下
verify_recaptcha
方法来测试条件的两种结果。
my controller code (DogMailsController) 我的控制器代码(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
My spec so far 到目前为止我的规格
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
What should I put above expect inorder to stub/mock out verify_recaptcha? 为了存根/模拟出verify_recaptcha,我应该超出预期的是什么? I tried
DogMailsController.stub(:verify_recaptcha).and_return(false)
but it doesn't seem to work. 我尝试了
DogMailsController.stub(:verify_recaptcha).and_return(false)
但它似乎不起作用。
您只需要存根controller.verify_recaptcha
,所以使用RSpec 3语法:
allow(controller).to receive(:verify_recaptcha).and_return(true)
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. Recaptcha gem的最新版本(我认为是3.2+ ) 在默认情况下会将 小部件隐藏在测试中 ,因此与Recaptcha成功相比,您更有可能最终需要模拟Recaptcha故障。 If you're testing a Rails controller directly, you can use a variant of infused's answer above :
如果您正在直接测试Rails控制器,则可以使用上述infused的答案的变体:
expect(controller).to receive(:verify_recaptcha).and_return(false)
If you're in a Rails 5 system or request spec, you may need to use expect_any_instance_of
: 如果您使用的是Rails 5系统或需要规格,则可能需要使用
expect_any_instance_of
:
expect_any_instance_of(MyController).to receive(:verify_recaptcha).and_return(false)
You could also use 您也可以使用
expect_any_instance_of(Recaptcha::Verify)
Note though that there are also situations (eg 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 请注意,尽管在某些情况下(例如服务器超时),
verify_recaptcha
将引发Recaptcha::RecaptchaError
而不是返回false,因此您可能也想测试一下-如上,但请替换
and_return(false)
with 同
and_raise(Recaptcha::RecaptchaError)
(As it happens, this will also (碰巧的是,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.