使用 Recaptcha 进行 Rails 功能测试
我的 UsersControllerTest 目前失败,因为我在 UsersController#create 中使用 verify_recaptcha。如何编写测试,以便使用 params[:user] 传递已知良好的验证码响应?我正在使用 reCAPTCHA,但我想这个问题适用于任何验证码实现。
这是我的 UsersController#create
def create
@user = User.new(params[:user])
if verify_recaptcha(@user) && @user.save
flash[:notice] = "Account registered!"
redirect_to new_order_url
else
flash.now[:error] = "Account not registered!"
render :action => :new
end
end
这是我的功能测试
test "should create user" do
assert_difference('User.count') do
post :create, :user => { :login => "jdoe",
:password => "secret",
:password_confirmation => "secret",
:first_name => 'john',
:last_name => 'doe',
:address1 => '123 Main St.',
:city => 'Anytown',
:state => 'XY',
:zip => '99999',
:country => 'United States',
:email => '[email protected]' }
end
end
此测试失败如下
4) Failure:
test_should_create_user(UsersControllerTest)
[(eval):3:in `each_with_index'
/test/functional/users_controller_test.rb:15:in `test_should_create_user']:
"User.count" didn't change by 1.
<3> expected but was
<2>.
My UsersControllerTest currently fails because I use verify_recaptcha in UsersController#create. How can I write my tests such that a known good CAPTCHA response is passed with params[:user]? I am using reCAPTCHA, but I suppose the question would apply to any CAPTCHA implementation.
Here is my UsersController#create
def create
@user = User.new(params[:user])
if verify_recaptcha(@user) && @user.save
flash[:notice] = "Account registered!"
redirect_to new_order_url
else
flash.now[:error] = "Account not registered!"
render :action => :new
end
end
and here is my functional test
test "should create user" do
assert_difference('User.count') do
post :create, :user => { :login => "jdoe",
:password => "secret",
:password_confirmation => "secret",
:first_name => 'john',
:last_name => 'doe',
:address1 => '123 Main St.',
:city => 'Anytown',
:state => 'XY',
:zip => '99999',
:country => 'United States',
:email => '[email protected]' }
end
end
This test fails as follows
4) Failure:
test_should_create_user(UsersControllerTest)
[(eval):3:in `each_with_index'
/test/functional/users_controller_test.rb:15:in `test_should_create_user']:
"User.count" didn't change by 1.
<3> expected but was
<2>.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用flexmock或mocha让verify_recaptcha的所有实例返回true:
我的应用程序中的这一行使创建测试通过,在我的应用程序上没有问题:
如果您在“创建”操作发生之前添加这一行,它应该可以工作。
另外,我还没有尝试过这个 recaptcha 插件,但这也可能对你有帮助:
http://www.fromdelhi。 com/2006/07/21/rails-captcha-and-testing-using-mock-objects/
Try using flexmock or mocha to have all instances of verify_recaptcha return true:
This line in my app made the create test pass without a problem on my app:
If you add this line before the "create" action takes place it should work.
Also, I haven't tried out this recaptcha plugin, but this might also be of help for you:
http://www.fromdelhi.com/2006/07/21/rails-captcha-and-testing-using-mock-objects/