我有以下控制器操作和测试。我刚开始使用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
答案 0 :(得分:2)
现在看来,您正在测试控制器内部模型特有的功能,应该在单元测试中。
我建议重新分解控制器,以包含更新所有者模型中所有者电子邮件所需的逻辑。通过这样做,您应该能够将控制器简化为简单的if update; else; end
类型语句,并大大简化控制器测试。将逻辑移入模型后,可以使用内置的Rails验证。
还需要考虑其他一些事项:
before_filters
。if request.post?
检查verify
或在`config / routes.rb'中创建路由。<强>参考强>: