views:

299

answers:

2

Can someone provide a strategy/code samples/pointers to test Captcha validations + Authlogic using Shoulda, Factory Girl and Mocha?

For instance, my UsersController is something like:

class UsersController < ApplicationController
validates_captcha

...
def create
...
if captcha_validated?
      # code to deal with user attributes
end
...
end

In this case, how do you mock/stub using Shoulda / Factory Girl / Mocha to test valid and invalid responses to the Captcha image?

Appreciate your help, Siva

A: 

I think it depends where captcha_validated? is defined, but you want to mock its return value and then write tests for each case. Something like this:

describe UsersController, "POST create" do
  context "valid captcha" do
    before do
      SomeCaptchaObject.expects(:captcha_validated?).returns(true)
    end
    # ...
  end
  context "invalid captcha" do
    before do
      SomeCaptchaObject.expects(:captcha_validated?).returns(false)
    end
    # ...
  end
end
rspeicher
Thanks rspeicher, the "captcha_validated?" is part of the Captcha plugin and is defined as below:module ValidatesCaptcha def self.included(base) base.extend(ClassMethods) end module ClassMethods def validates_captcha helper CaptchaHelper include ValidatesCaptcha::InstanceMethods end end module InstanceMethods def captcha_validated? CaptchaUtil::encrypt_string(params[:captcha].to_s.gsub(' ', '').downcase) == params[:captcha_validation] end end end I will try your suggestion and report back.Thanks again - Siva
Siva
A: 

I was able to solve with this setup:

class UsersControllerTest < ActionController::TestCase

  context "create action" do

    context "valid user with valid captcha" do

      setup do
        User.any_instance.stubs(:valid?).returns(true)
        @controller.stubs(:captcha_validated?).returns(true)

        post :create, :user => Factory.attributes_for(:user, :captcha => "blahblah")
      end

      should_redirect_to("user home") { user_path(@user) }
    end

    context "valid user with invalid captcha" do
      setup do

        User.any_instance.stubs(:valid?).returns(true)
        @controller.stubs(:captcha_validated?).returns(false)

        post :create, :user => Factory.attributes_for(:user, :captcha => "blahblah")
      end

      should_render_template :new

    end
  end
end

Thanks.

Siva