【问题标题】:Testing gems within a Rails App在 Rails 应用程序中测试 gem
【发布时间】:2011-02-23 11:36:34
【问题描述】:

我正在尝试测试我的服务是否正确调用 Anemone.crawl。我有以下代码:

spider_service.rb

class SpiderService < BaseService
  require 'anemone'
  attr_accessor :url
  def initialize(url)
    self.url = url
  end
  def crawl_site
    Anemone.crawl(url) do |anemone|
    end
  end
end

spider_service_spec.rb

require 'spec_helper'
require 'anemone'

describe SpiderService do
  describe "initialize" do
    let(:url) { mock("url") }

    subject { SpiderService.new(url) }

    it "should store the url in an instance variable" do
      subject.url.should == url
    end
  end

  describe "#crawl_site" do
    let(:spider_service) { mock("spider service") }
    let(:url) { mock("url") }

    before do
      SpiderService.stub(:new).and_return(spider_service)
      spider_service.stub(:crawl_site)
      Anemone.stub(:crawl).with(url)
    end

    subject { spider_service.crawl_site }

    it "should call Anemone.crawl with the url" do
      Anemone.should_receive(:crawl).with(url)
      subject
    end

  end
end

这是我遇到的错误,但我无法理解,因为我可以在 Rails 控制台中调用该服务,并在提供有效 URL 时从 Anemone 获取数据:

Failures:

  1) SpiderService#crawl_site should call Anemone.crawl with the url
     Failure/Error: Anemone.should_receive(:crawl).with(url)
     (Anemone).crawl(#<RSpec::Mocks::Mock:0x82bdd454 @name="url">)
         expected: 1 time
         received: 0 times
     # ./spec/services/spider_service_spec.rb:28

请告诉我我忘记了一些愚蠢的事情(那我可以责怪缺乏咖啡,而不是普遍的无能!)

感谢您的宝贵时间,

Gav

【问题讨论】:

  • 顺便说一句,这个问题与 Rails 无关。

标签: ruby-on-rails ruby rspec gem


【解决方案1】:

您的主体在您创建的模拟对象(mock("spider_service"))上调用一个方法,而不是真正的 SpiderService 对象。您还将模拟蜘蛛服务上的调用存根不做任何事情,因此在主题中调用它不会做任何事情,这就是您的测试失败的原因。

此外,您已经在 SpiderService 上存根 new(尽管您从未调用它)以返回一个模拟对象。当您测试 SpiderService 时,您将希望拥有该类的真实实例,否则方法调用的行为将不会像在该类的真实实例上那样。

以下应该可以实现您想要的:

describe "#crawl_site" do
  let(:spider_service) { SpiderService.new(url) }
  let(:url) { mock("url") }

  before do
    Anemone.stub(:crawl).with(url)
  end

  subject { spider_service.crawl_site }

  it "should call Anemone.crawl with the url" do
    Anemone.should_receive(:crawl).with(url)
    subject
  end

end

您可能还希望将 require 'anenome' 移到类定义之外,以便在其他地方使用。

【讨论】:

  • 我写了很多不同的方法来尝试让它工作,但其中的某个地方完全迷失了。谢谢你救了我詹姆斯——完全的启蒙现在已经不远了!
猜你喜欢
  • 1970-01-01
  • 2012-01-20
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
相关资源
最近更新 更多