【问题标题】:Understanding Rspec Stubs and Controller Tests了解 Rspec 存根和控制器测试
【发布时间】:2013-01-04 23:29:41
【问题描述】:

我第一次使用存根时,我有一个控制器,它在调用页面时运行一个方法。如果该方法返回空,我希望重定向回主页。因此我的控制器看起来像这样

def jobs
  if scrap_cl().empty?
    redirect_to home_path
    flash[:error] = "Nothing found this month!"
  end
end

对于我的测试,我想在该方法返回空时测试重定向。到目前为止我有这个

context "jobs redirects to homepage when nothing returned from crawlers" do
  before do
    PagesController.stub(:scrap_cl).and_return("")
    get :jobs
  end

  it { should respond_with(:success) }
  it { should render_template(:home) }
  it { should set_the_flash.to("Nothing found this month!")}      

end

当我运行 rpsec 时,我得到两个错误,一个在渲染模板上,另一个在 flash 上。因此,它把我送到了工作页面。我对存根和测试做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec stub


    【解决方案1】:

    你的存根将存根出一个名为scrap_cl 的类方法,它永远不会被调用。你想要实例方法。您可以通过 RSpec 的any_instance 轻松实现这一点:

    PagesController.any_instance.stub(:scrap_cl).and_return("")
    

    这将导致 PagesController 的所有实例都存根该方法,这正是您在这里真正想要的。

    【讨论】:

      猜你喜欢
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 2011-03-11
      • 1970-01-01
      相关资源
      最近更新 更多