RSpec макет или заглушка супер в модели - PullRequest
3 голосов
/ 26 ноября 2010

Как мне проверить эту крошечную часть модуля с помощью super?(суперкласс - action_dispatch-3.0.1 тестирование / интеграция ...) Модуль включен в спецификацию / запросы на перехват post :

module ApiDoc
  def post(path, parameters = nil, headers = nil)
    super
    document_request("post", path, parameters, headers) if ENV['API_DOC'] == "true"
  end
  ...
end

Я не хочу, чтобы он запускалсяActionDispatch :: Integration-что угодно, но я не знаю how to mock or stub super, чтобы провести его модульное тестирование.

Модуль используется только в пределах спецификаций и будет иметь 100% покрытие тестами, что подтверждает эти виды метрик.как бесполезно.Мне нужно проверить его.

Например, при необходимости, так я использую модуль ApiDoc

require 'spec_helper'

describe "Products API" do
  include ApiDoc  ############## <---- This is my module
  context "POST product" do
    before do
      @hash = {:product => {:name => "Test Name 1", :description => "Some data for testing"}}
    end

    it "can be done with JSON" do
      valid_json = @hash.to_json
      ############### the following 'post' is overriden by ApiDoc
      post("/products.json",valid_json,
       {"CONTENT_TYPE" => "application/json",
        "HTTP_AUTHORIZATION" => ActionController::HttpAuthentication::Basic.encode_credentials("user", "secret")})
      response.should be_success
    end
  end
end

Ответы [ 2 ]

4 голосов
/ 26 ноября 2010

Вы можете проверить, вызывается ли метод для класса 'super'

ActionDispatch::Integration.any_instance.should_receive(:post)

Поскольку ApiDock требуется только для ваших тестов, вы также можете перезаписать метод post с помощью alias_method_chain:

ActionDispatch::Integration.instance_eval do
  def post_with_apidoc(path, parameters = nil, headers = nil)
    post_without_apidoc
    if ENV['API_DOC'] == "true"
      document_request("post", path, parameters, headers)
    end
  end
  alias_method_chain :post, :apidoc
end
1 голос
/ 29 ноября 2010

Это всего лишь дополнение к ответу.Вот так я и закончил тестировать

require 'spec_helper'

describe 'ApiDoc' do
  include ApiDoc

  it "should pass the post to super, ActionDispatch" do
    @path = "path"
    @parameters = {:param1 => "someparam"}
    @headers = {:aheader => "someheaders"}
    ActionDispatch::Integration::Session.any_instance.expects(:post).with(@path, @parameters, @headers)
    post(@path, @parameters, @headers)
  end
end

class DummySuper
  def post(path, parameters=nil, headers=nil)
    #How to verify this is called?
  end
end
class Dummy < DummySuper
  include ApiDoc
end

describe Dummy do

  it "should call super" do
    subject.expects(:enabled?).once.returns(true)
    #how to expect super, the DummySuper.post ?
    path = "path"
    parameters = {:param1 => "someparam"}
    headers = {:aheader => "someheaders"}
    subject.expects(:document_request).with("post", path, parameters, headers)
    subject.post(path, parameters, headers)
  end
end

и слегка модифицированный ApiDoc.

module ApiDoc
  def enabled?
    ENV['API_DOC'] == "true"
  end

  def post(path, parameters = nil, headers = nil)
    super
    document_request("post", path, parameters, headers) if enabled?
  end

private
  def document_request(verb, path, parameters, headers)
  ...
  end
end

Я мог проверить super.post в первом тесте, но я все еще не могу понять, как это сделать с моими спецификациями класса Dummy.

...