Shouldaでこのコントローラーアクションを適切にテストする方法は?
-
19-08-2019 - |
質問
次のコントローラーアクションとテストがあります。私はShouldaでテストするのは初めてで、さらにテストできるコントローラーの領域があることを知っています。たとえば、フラッシュメッセージとレンダリングの検証。
私の質問は、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
解決
今、コントローラー内のモデルに固有の機能をテストしているようです。これは単体テストに含まれているはずです。
所有者モデル内で所有者の電子メールを更新するために必要なロジックを含めるようにコントローラーをリファクタリングすることをお勧めします。そうすることで、コントローラーを単純なif update; else; end
タイプのステートメントに単純化し、コントローラーのテストを大幅に単純化できるはずです。ロジックをモデルに移動したら、組み込みのRails検証を使用できます。
考慮すべき他のいくつかの事項:
- POSTアクションの完了後にリダイレクトすることにより、ユーザーが誤って二重投稿するのを防ぎます(ほとんどのブラウザーは、ユーザーが試行したときに文句を言います)。
- @siteのチェックと、@ ownerへの割り当てを
before_filters
に移動します(これがコントローラー内で複数回行われる場合)。 -
if request.post?
をverify
でチェックするか、 `config / routes.rb 'でルートを作成する必要はありません。
参照:
所属していません StackOverflow