アンフォローしようとしているユーザーが存在しないときに、私はフラッシュエラーメッセージを設定し、ユーザーを元のページにリダイレクトする例外をスローします。RSpecを使用して既にスタブされたコントローラメソッドでメソッドをスタブする方法はありますか?
twitterの宝石へのすべてのアクセスは、Mock_modelを有効にするためにActiveModel :: Namingを拡張する通常のrubyクラスであるTwitterManagerクラスによって処理されます。
今、私は実際にどのようにこれをテストすべきかを考え出すのに苦労しています。以下のコードは動作しますが、非常に間違っていると感じます。 twitter.unfollowメソッドをスタブする唯一の方法は、controller.send(:twitter).stub(:unfollow).and_raise(Twitter :: Error :: NotFound.new( ""、{}))でした。
私はTwitterManager.any_instance.stub(:unfollow)を使ってみましたが、それは明らかに私が思ったことをしませんでした。
どうすればこの問題を改善できますか?どのようなことを私は完全に誤解していますか?
スペック
describe TwitterController do
before(:each) do
controller.stub(:twitter).and_return(mock_model("TwitterManager", unfollow: true, follow: true))
end
it "unfollows a user when given a nickname" do
@request.env['HTTP_REFERER'] = '/followers'
post 'unfollow', id: "existing_user"
response.should redirect_to followers_path
end
describe "POST 'unfollow'" do
it "does not unfollow a user that does not exist" do
controller.send(:twitter).stub(:unfollow).and_raise(Twitter::Error::NotFound.new("", {}))
@request.env['HTTP_REFERER'] = '/followers'
post 'unfollow', id: "non_existing_user"
flash[:error].should_not be_nil
flash[:error].should have_content("not found, could not unfollow")
response.should redirect_to followers_path
end
end
コントローラ
def unfollow
begin
twitter.unfollow(params[:id])
respond_to do |format|
format.html { redirect_to :back, notice: "Stopped following #{params[:id]}" }
end
rescue Twitter::Error::NotFound
redirect_to :back, :flash => { error: "User #{params[:id]} not found, could not unfollow user" }
end
end
[全コード]
private
def twitter
twitter_service ||= TwitterFollower.new(current_user)
end
RSpecの2.8.0 のRails 3.2.0