ruby on rails - How do I fake a recaptcha in a unit test?

Keywords:ruby  on  rails 


I'm using Rails 5 and have a form with a Google recaptcha. I use the Rails gem for this

gem "recaptcha", require: "recaptcha/rails"

So I have a simple form with

<%= form_for @comment, :html => {:class => "commentsForm"} do |f| %>
  <div class="field">
    <%= f.label :description, 'Your Comments' %><br>
    <%= f.text_area :description %>
  <%= recaptcha_tags %>
  <div class="actions">
    <%= submit_tag 'Submit', :class => 'btn-feedback' %>
<% end %>

and my controller to deal with this is

  def create
    @comment =[:comment].permit(:description))
    @comment.user = current_user
    if verify_recaptcha(model: @comment)

but how do I write a unit test to test the controller method? I don't know how to "fake" the recaptcha submission. This is all I have

  test "do submit comment" do
    post comments_url, params: { comment: { description: "Some comments"} }

    # Verify we got the proper response
    assert_response :success

but this fails. How do I fake a recaptcha in a unit test?

2 Answers: 

FOR V2 Only:

With the following test keys, you will always get No CAPTCHA and all verification requests will pass.


Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

Source: Google reCAPTCHA FAQs Page


Not sure what you mean with "faking". If it is about getting a verification return with a low score (i.e. high robot probability), you could spoof the User Agent, if this is possible in your test routine.

See this answer on SO : Is it possible to force fail a recaptcha v2 for testing purposes? (I.e. pretend to be a robot)