Gem Version Travis Build Status Coverage Status Code Climate Gem Dependencies

ActsAsTextcaptcha provides spam protection for your Rails models using logic questions from the excellent TextCaptcha web service (by Rob Tuley. It is also possible to configure your own captcha questions (instead, or as a fallback in the event of any API issues).

This gem is actively maintained, has good test coverage and is compatible with Rails >= 3 (including Rails 4 & 5) and Ruby >= 2.1. If you have issues please report them here.

Logic questions from the web service are aimed at a child's age of 7, so they can be solved easily by even the most cognitively impaired users. As they involve human logic, questions cannot be solved by a robot. There are both advantages and disadvantages in using logic questions over image based captchas, find out more at TextCaptcha.


Try a working demo here!

Or click below to deploy your own example Rails app to Heroku (already configured with acts_as_textcaptcha). See here for more details.



First add the following to your Gemfile, then bundle install;

gem 'acts_as_textcaptcha'

Add the following code to models you would like to protect;

class Comment < ApplicationRecord
  # (this is the simplest way to configure the gem)
  acts_as_textcaptcha :api_key => 'TEXTCAPTCHA_API_IDENTITY'

Your TEXTCAPTCHA_API_IDENTITY should be some reference to yourself (e.g. an email address, domain or similar where if there are problems with your usage you can be contacted).

Next, in your controller's new action generate and assign the logic question for the record, like so;

def new
  @comment =

Finally, in the view add the textcaptcha question and answer fields to your form using the textcaptcha_fields helper. Feel free to arrange the HTML within this block as you like;

<%= textcaptcha_fields(f) do %>
  <div class="field">
    <%= f.label :textcaptcha_answer, @comment.textcaptcha_question %><br/>
    <%= f.text_field :textcaptcha_answer, :value => '' %>
<% end %>

NOTE: If you'd rather NOT use this helper and prefer to write your own form elements, take a look at the HTML produced from this helper method here.

NOTE: The defaults for cache configuration changed with Rails 5 and this gem requires a working Rails.cache store to exist.

NOTE: These installation steps changed with v4.0.0 of this gem. If you are having problems please refer to the 3.0 upgrade guide.

Toggling TextCaptcha

You can toggle textcaptcha on/off for your models by overriding the perform_textcaptcha? method. If it returns false, no questions will be fetched from the web service and captcha validation is disabled.

This is useful for writing your own custom logic for toggling spam protection on/off e.g. for logged in users. By default the perform_textcaptcha? method checks if the object is a new (unsaved) record.

So out of the box, spam protection is only enabled for creating new records (not updating). Here is a typical example showing how to overwrite the perform_textcaptcha? method, while maintaining the new record check.

class Comment < ApplicationRecord
  acts_as_textcaptcha :api_key => 'TEXTCAPTCHA_API_IDENTITY'

  def perform_textcaptcha?
    super && user.admin?

Configuration options

You can configure captchas with the following options;

  • api_key (_required_) - reference to yourself (e.g. your email - to identify calls to the API)
  • questions (_optional_) - array of question and answer hashes (see below) A random question from this array will be asked if the web service fails OR if no api_key has been set. Multiple answers to the same question are comma separated (e.g. 2,two). Don't use commas in your answers!
  • cache_expiry_minutes (_optional_) - minutes for answers to persist in the cache (default 10 minutes), see below for details
  • http_read_timeout (_optional_) - Net::HTTP option, seconds to wait for one block to be read from the remote API
  • http_open_timeout (_optional_) - Net::HTTP option, seconds to wait for the connection to open to the remote API

For example;

class Comment < ApplicationRecord
  acts_as_textcaptcha :api_key              => 'TEXTCAPTCHA_API_IDENTITY',
                      :http_read_timeout    => 60,
                      :http_read_timeout    => 10,
                      :cache_expiry_minutes => 10,
                      :questions            => [{ 'question' => '1+1', 'answers' => '2,two' },
                                                { 'question' => 'The green hat is what color?', 'answers' => 'green' }]

YAML config

The gem can be configured for models individually (as shown above) or with a config/textcaptcha.yml file. The config file must have an api_key defined and/or an array of questions and answers. Any options defined inline in model classes take preference over the global configuration in textcaptcha.yml.

The gem comes with a handy rake task to copy over a textcaptcha.yml template to your config directory;

rake textcaptcha:config

Configuring without the TextCaptcha web service

To use only your own logic questions, simply omit the api_key from the configuration and define at least one logic question and answer (see above).


The gem uses the standard Rails I18n translation approach (with a fall-back to English). Unfortunately at present, the TextCaptcha web service only provides logic questions in English.

              incorrect: "is incorrect, try another question instead"
              expired: "was not submitted quickly enough, try another question instead"
        textcaptcha_answer: "TextCaptcha answer"

Without ActiveRecord

It is possible to use this gem without ActiveRecord. As an example, take a look at the Contact model used in the test suite here.

Testing and docs

In development you can run the tests and rdoc tasks like so;

  • rake test (all tests)
  • rake test:coverage (all tests with code coverage reporting)
  • appraisal rake test (all tests with all gemfile variations)
  • appraisal rails-3 rake test (all tests using a specific gemfile)
  • rake rdoc (generate docs)

This gem uses appraisal to run the test suite with multiple versions of Rails.

What does the code do?

The gem contains two parts, a module for your ActiveRecord models, and a single view helper method. The ActiveRecord module makes use of two futher classes, TextcaptchaApi and TextcaptchaCache.

A call to @model.textcaptcha in your controller will query the TextCaptcha web service. A GET request is made with Net::HTTP and parsed using the default Rails ActiveSupport::XMLMini backend. A textcaptcha_question and a random cache key are assigned to the record. An array of possible answers is also stored in the TextcaptchaCache with this random key. The cached answers have (by default) a 10 minute TTL in your cache. If your forms take more than 10 minutes to be completed you can adjust this value setting the cache_expiry_minutes option. Internally TextcaptchaCache wraps Rails.cache and all cache keys are name spaced.

On saving, validate_textcaptcha is called on @model.validate checking that the @model.textcaptcha_answer matches one of the possible answers (retrieved from the cache). By default, this validation is only carried out on new records, i.e. never on update, only on create. All attempted answers are case-insensitive and have trailing/leading white-space removed.

Regardless of a correct, or incorrect answer the possible answers are cleared from the cache and a new random key is generated and assigned. An incorrect answer will cause a new question to be prompted. After one correct answer, the answer and a mutating key are sent on further form requests, and no question is presented in the form.

If an error or timeout occurs during API fetching, ActsAsTextcaptcha will fall back to choose a random logic question defined in your options (see above). If the web service fails or no API key is specified AND no alternate questions are configured, the @model will not require textcaptcha checking and will pass as valid.

For more details on the code please check the documentation. Tests are written with MiniTest. Pull requests and bug reports are welcome.


What do you need?

  • Rails >= 3 (including Rails 4 & 5)
  • Rails.cache - a basic cache configuration is necessary
  • Ruby >= 2.1

NOTE: The built-in TextcaptchaCache class directly wraps the Rails.cache. An alternative TextcaptchaCache implementation will be necessary if Rails.cache is not available.

Rails 2 Support

Support for Rails 2 was dropped with the release of v4.1.0. If you would like to continue to use this gem with an older version of Rails (>= 2.3.8), please lock your Gemfile with version 4.0.0. Like so;

# in your Gemfile
gem 'acts_as_textcaptcha', '=4.0.0'

# or in config/environment.rb
config.gem 'acts_as_textcaptcha', :version => '=4.0.0'

Check out the README for this release for further instructions.


Who's who?


This gem is used in a number of production websites and apps. It was originally extracted from code developed for Bugle. If you're happily using acts_as_textcaptcha in production, please let me know and I'll add you to this list!