【问题标题】:How to stub a method on an already stubbed controller method with RSpec?如何使用 RSpec 在已经存根的控制器方法上存根方法?
【发布时间】: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


    【解决方案1】:

    您可以通过将模拟 TwitterManager 保存为 before 块中的实例变量并直接在该对象上存根来清理它:

    describe TwitterController do
    
      before(:each) do
        @twitter = mock_model("TwitterManager", unfollow: true, follow: true)
        controller.stub(:twitter).and_return(@twitter)
      end
    
      # ...
    
      describe "POST 'unfollow'" do
        it "does not unfollow a user that does not exist" do
          @twitter.stub(:unfollow).and_raise(Twitter::Error::NotFound.new("", {}))
          # ...
        end
      end
    end
    

    但我不会说你在做的是“非常错误”:-)

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 2011-05-09
      • 2015-08-31
      相关资源
      最近更新 更多