1

我有以下控制器动作和测试。我是使用 Shoulda 进行测试的新手,我知道我的控制器的某些区域可以进一步测试。例如,我的 Flash 消息以及验证渲染。

所以我的问题是,我将如何在 Shoulda 中正确测试此控制器操作?

我的控制器操作(名称已更改以保护无辜者):

def my_action
  return redirect_to(root_url) if @site.nil?
  @owner = current_site.owner
  if request.post?
    if params[:password].blank? || params[:email].blank?
      flash[:error] = "You must fill in both the e-mail and password fields"
      render :action => "my_action"
    else
      if @owner.authenticated?(params[:password])
        @owner.login = params[:email]
        @owner.save!
        @owner.do_some_method
        flash[:success] = "Success."
        render :action => "my_action"
      else
        flash[:error] = "Incorrect password"
        render :action => "my_action"
      end
    end      
  end  
end

我的测试:

context "on POST to :my_action" do
  setup do
    Owner.any_instance().expects(:do_some_method)
    post :my_action, :email => 'foo@bar.com', :password => 'test'
  end
  should_assign_to :owner
  should "Change name and verify password and resend activation key" do
    assert_equal true, assigns(:owner).authenticated?('test')
    assert_equal 'foo@bar.com', assigns(:owner).login
  end
  should_respond_with :success
end
4

1 回答 1

2

现在,您似乎正在测试特定于控制器内部模型的功能,这应该在单元测试中。

我建议重构您的控制器,以在所有者模型中包含更新所有者电子邮件所需的逻辑。通过这样做,您应该能够将控制器简化为简单的if update; else; end类型语句,并大大简化控制器测试。将逻辑移入模型后,您可以使用内置的 Rails 验证。

需要考虑的其他几件事:

  • 在您的 POST 操作完成后重定向,可防止用户意外重复发布(大多数浏览器在用户尝试时会抱怨)。
  • before_filters如果在控制器内多次执行此操作,则将对@site 的检查以及对@owner 的分配移动到。
  • 您可以避免在 `config/routes.rb' 中检查if request.post?verify创建路由。

参考资料

于 2009-01-23T16:44:25.610 回答