【问题标题】:Rspec Stubbing BehaviorRspec 存根行为
【发布时间】:2013-01-31 20:43:28
【问题描述】:

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

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

我的控制器测试是这样的:

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']

我已经被困在这个问题上太久了;非常感谢任何帮助!

【问题讨论】:

  • 这是您正在测试的真实文件,还是您对其进行了伪编码?我问的原因是因为您没有在示例中的任何地方存根load_articles,而是在存根meth1meth2。您看到的行为不应该发生在这样的上下文块中正确存根。
  • 我现在猜测 meth1meth2 只是 load_articles 调用 Article 的东西,但可能还有更多的东西可以帮助诊断它。关于这些方法的一些细节可能有用。另外,那里是否有任何可能干扰的缓存/记忆?

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多