ruby-on-rails - 如果没有 any_instance,如何断言没有进行方法调用?

标签 ruby-on-rails testing rspec tdd

我有一个类,在一种情况下应该调用:my_method,但在另一种情况下不能调用方法:my_method。我想测试这两种情况。另外,我希望测试记录不应调用 :my_method 的情况。

Using any_instance is generally discouraged ,所以我很乐意学习一种替代它的好方法。

此代码片段是我想要编写的测试类型的简化示例。

class TestSubject
  def call
    call_me
  end

   def call_me; end
   def never_mind; end
end

require 'rspec'

spec = RSpec.describe 'TestSubject' do
  describe '#call' do
    it 'calls #call_me' do
      expect_any_instance_of(TestSubject).to receive(:call_me)
      TestSubject.new.call
    end

    it 'does not call #never_mind' do
      expect_any_instance_of(TestSubject).not_to receive(:never_mind)
      TestSubject.new.call
    end
  end
end

spec.run # => true

它有效,但使用 expect_any_instance_of 方法,不推荐使用。

如何更换?

最佳答案

我会做那样的事

describe TestSubject do
  describe '#call' do
    it 'does not call #something' do 
      subject = TestSubject.new
      allow(subject).to receive(:something)

      subject.call

      expect(subject).not_to have_received(:something)
    end
  end
end

希望这对您有所帮助!

关于ruby-on-rails - 如果没有 any_instance,如何断言没有进行方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52889179/

相关文章:

ruby-on-rails - Rails 4、Devise、Omniauth、Cancan、Twitter API

ruby-on-rails - 从随机 :id to :username in rails 更改路由 URL

java - 使用 Junit 进行多步测试

jquery - geocomplete_rails 和 Uncaught ReferenceError : google is not defined

ruby-on-rails - 无法启动 Web 应用程序 - Rails 和 CentOS

java - Java 模糊测试库

android - 如何找到运行 64 位操作系统的 Android 手机进行软件测试?

ruby - 失败时 pretty-print 数组

ruby-on-rails - 测试速度 : ActiveRecord use_transactional_fixtures vs. DatabaseCleaner.strategy = :transaction

ruby-on-rails - 在嵌套 Rspec 上下文中继承示例