【发布时间】:2012-02-25 15:53:15
【问题描述】:
当我试图取消关注的用户不存在时,我会抛出一个异常,该异常会设置一个 flash 错误消息并将用户重定向回他们所在的页面。
所有对 twitter gem 的访问都由 TwitterManager 类处理,该类是一个常规的 ruby 类,它扩展 ActiveModel::Naming 以启用 mock_model。
现在我很难弄清楚应该如何测试它。下面的代码有效,但感觉非常错误。我可以存根 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 导轨 3.2.0
【问题讨论】:
标签: ruby-on-rails rspec mocking