Skip to content

Instantly share code, notes, and snippets.

@elvisgiv
Last active April 27, 2016 14:35
Show Gist options
  • Save elvisgiv/0fb0e9ad45809fe84753f08c29a7c798 to your computer and use it in GitHub Desktop.
Save elvisgiv/0fb0e9ad45809fe84753f08c29a7c798 to your computer and use it in GitHub Desktop.

#Expect vs Allow есть метод, который вызывает внутри себя еще два метода

  def self.get_cluster_info(cluster)
    data = {cluster: cluster.to_hash, settings: cluster.options_hash_public}
    Response.res_data(data)
  end

задача. написать тесты, которые определяют вызывается ли метод внутри данного метода

RSpec.describe "cluster info", :type => :request do
  before :each do
    @lib = Gexcore::ClustersService

    stub_create_user_all
    stub_create_cluster_all
  end

  describe 'ClustersService.get_cluster_info' do
    before :each do
      @cluster_for_error = double(Cluster)
    end

    it 'to_hash_method' do
      expect(@cluster_for_error).to receive(:to_hash).and_return("test")
      allow(@cluster_for_error).to receive(:options_hash_public).and_return("test2")

      res = @lib.get_cluster_info(@cluster_for_error)
    end

    it 'options_hash_public_method' do
      allow(@cluster_for_error).to receive(:to_hash).and_return("test")
      expect(@cluster_for_error).to receive(:options_hash_public).and_return("test2")

      # work
      res = @lib.get_cluster_info(@cluster_for_error)
    end

  end
end

убираем из метода self.get_cluster_info(cluster) cluster.to_hash и оставляем вместо него {}

  def self.get_cluster_info(cluster)
    data = {cluster: {}, settings: cluster.options_hash_public}
    Response.res_data(data)
  end

в этом случае у нас проходит только options_hash_public_method тест и, соостветственно,

если теже действия провести с cluster.options_hash_public, то пройдет только to_hash_method тест

это становится возможным потому, что allow полностью заменяет возвращаемое методом значение своим значением НЕ вызывая его(метод), а expect полностью заменяет возвращаемое методом значение своим значением СНАЧАЛА вызвав его(метод), если такого метода нет - выдает ошибку.

http://stackoverflow.com/questions/28006913/rspec-allow-expect-vs-just-expect-and-return

rspec/rspec-mocks#557

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment