ruby-on-rails - Rspec stub 行为

标签 ruby-on-rails testing rspec functional-testing

我在使用 stub 时遇到了一些问题,我想我一定是误解了它们的工作原理。

stub 是否只存在于它们被创建的上下文中?这是我的期望,但根据我的经验,如果我在一个上下文中 stub 一个方法,它仍然存在于另一个上下文中。

我的 Controller 测试与此类似:

describe '.load_articles' do
  context 'articles' do
    before(:each) do
      Article.stub_chain(:meth1, :meth2).and_return(['article'])
    end
    it 'sets articles' do
      controller.load_articles.should == ['article']
    end

  end
  context 'no articles' do
    before(:each) do
      Article.stub_chain(:meth1, :meth2).and_return([])
    end
    it 'sets article' do
      controller.load_articles.should == []
    end

  end
end

对于第二个示例,controller.load_articles 在我期待 []

时仍返回 ['article']

我已经坚持这个太久了;非常感谢任何帮助!

最佳答案

每个示例后都会清除 stub 。你可以很容易地证明这一点:

class Numero; end

describe Numero do
  context "Uno" do
    before do
      Numero.stub_chain(:meth1, :meth2) { 'uno' }
    end
    it "unos" do
      Numero.meth1.meth2.should == 'uno'
    end
  end
  context "Dos" do
    before do
      Numero.stub_chain(:meth1, :meth2) { 'dos' }
    end
    it "dosses" do
      Numero.meth1.meth2.should == 'dos'
    end
  end
end

关于ruby-on-rails - Rspec stub 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14634791/

相关文章:

ruby-on-rails - 在救援中添加模型验证错误

testing - 使用 Julia,有没有办法创建一个测试/临时/一次性环境?

ruby-on-rails - 为什么 Kernel#require 占用了我 45% 的获取时间?

ruby-on-rails - 如何使 Capybara 中的 rails 错误显示在 rspec 功能中?

ruby - 如何对严重依赖于其他类的类进行单元测试?

mysql - 如何将 ruby​​ on Rails 应用程序导入到另一台计算机

ruby-on-rails - Rails 3 路由

ruby-on-rails - 查看测试和 Devise 的 current_user

ruby-on-rails - 在 Rails 上运行迁移后如何生成模型

testing - 模拟 bufio.NewScanner 的标准输出流