【问题标题】:What a test should test with Rspec in Ruby on Rails application在 Ruby on Rails 应用程序中应该使用 Rspec 测试什么
【发布时间】:2018-11-25 08:34:14
【问题描述】:

我是 Rspec 的初学者,实际上我们要求我对一些已经构建但从未测试过的方法进行 Rspec 测试(他们不会在构建方法之前编写测试)。

现在我很想知道如何测试我的方法,这里是示例:

 class ConnectorJob < ActiveJob::Base

  queue_as :connector

  def perform(tenant_id = nil, debug = false)
    tenant_to_sync = Tenant.to_sync(tenant_id)
    return if tenant_to_sync.empty?
    tenant_to_sync.each do |tenant|
      service = MyAPP::ContactToSync.new(tenant, debug).call
      if service.success?
        ConnectorService::Synchronization.new(
          tenant, service.data, debug
        ).call
      end
    end
  end
end

我应该对此进行什么测试?我应该测试返回值是否正确或是否调用了其他方法?

这是我尝试做的事情

    require "rails_helper"

RSpec.describe ConnectorJob, type: :job do
  it 'is in connector queue' do
    expect(ConnectorJob.new.queue_name).to eq('connector')
  end

  describe 'perform' do
    let (:tenant) { create(:tenant) }
    let (:job) { ConnectorJob.new.perform(tenant.id) }

  context 'with empty tenant' do
      it { expect(ConnectorJob.new.perform(@tenant.id)).to eq nil }
    end

    context 'with tenant' do
      it { expect(ConnectorJob.new.perform(tenant.id)).to eq job }
    end
  end
end

如您所见,我的最后一个测试没有意义,但我不知道应该在我的 Rspec 上写什么来预测这种方法的结果。

如果我检查我的 Rspec 覆盖率,Rspec 告诉我我覆盖了 100% 的方法,但我不确定这是正确的。

我希望我很清楚,请随时问我更多细节。

谢谢大家

【问题讨论】:

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


    【解决方案1】:

    我认为你应该测试最终结果,我的意思是调用后的结果 ConnectorService::Synchronization.new(...).call 并测试三个案例,例如如果此调用创建新用户,您应该对其进行测试:

    如果tenant_to_sync.empty? == true

     context 'with empty tenant' do
       it { expect(ConnectorJob.new.perform(@tenant.id)).to change(User.count).by(0) }
     end
    

    如果service.success? == false

    context 'MyAPP::ContactToSync return false' do
       it { expect(ConnectorJob.new.perform(@tenant.id)).to change(User.count).by(0) }
     end
    

    如果service.success? == true

    context 'success' do
       it { expect(ConnectorJob.new.perform(@tenant.id)).to change(User.count).by(1) }
     end
    

    应该足以涵盖所有场景。

    【讨论】:

    • 您好,感谢您的回答。但我不知道如何测试最终结果。最终结果应该是一个结构,但我如何才能在我的尊重上创建正确的结构,正如我在我的例子中展示的那样,我做了expect(perform).to eq jobjobperform 相同,所以我认为它没有意义,因为即使方法不正确,它也将是平等的。
    • @Imnotgood,你可以在测试之前存根方法ConnectorService::Synchronization.new 并返回你想要的。然后你就可以确定该方法被正确调用了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多