0

有人可以提供策略/代码示例/指针来测试 Captcha 验证 + Authlogic 使用 Shoulda、Factory Girl 和 Mocha 吗?

例如,我的 UsersController 类似于:

class UsersController < ApplicationController
validates_captcha

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

在这种情况下,您如何使用 Shoulda / Factory Girl / Mocha 模拟/存根来测试对验证码图像的有效和无效响应?

感谢您的帮助,湿婆

4

2 回答 2

0

我能够用这个设置解决:

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

谢谢。

于 2010-06-07T21:36:51.763 回答
0

我认为这取决于captcha_validated?定义的位置,但是您想模拟其返回值,然后为每种情况编写测试。像这样的东西:

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
于 2010-06-06T22:01:55.350 回答