ruby - 如何使用不同的参数模拟同一个数据库调用两次并将所有响应值与值数组进行匹配?

标签 ruby testing rspec mocking

我有一个类有一个方法 team_names。在这个方法中,我遍历每个团队对象(数组中总是只有两个团队),格式为 { id: 'some_id' } 并向 Mongo 数据库发出请求,尝试检索每个来自 teams 集合的团队。最后我返回一组团队名称。我使用此数据生成用户电子邮件的主题。

我想测试我是否得到了正确的团队。所以我有一个从数据库中获取团队的模拟。

这是我的类(class):

class MyEmail
  def initialize(event)
    @teams = event['performers']
  end

  def team_names
    @teams.map do |team| 
      MyMongoGem::DB['teams'].find('_id' => BSON::ObjectId.from_string(team['id'])).first['name']
    end
  end

  def subject
    "Hello from - #{team_names.join(' and ')"
  end

  def deliver!
    # send email
  end
end

现在测试看起来像这样:

describe MyEmail do
  let(:team_1_id) { BSON::ObjectId.new }
  let(:team_2_id) { BSON::ObjectId.new }
  let(:team_1) do
    {
      'id' => team_1_id.to_s,
      'name' => 'Cats'
    }
  end
  let(:team_2) do
    {
      'id' => team_2_id.to_s,
      'name' => 'Dogs'
    }
  end
  let(:teams) { [team_1, team_2] }
  let(:event) { { name: "some event", performers: teams} }

  subject { described_class.new(event) }

  before do
    allow(MyMongoGem::DB['teams']).to receive_message_chain(:find, :first)
      .with(any_args)
      .and_return team_1

    subject.deliver!
  end

  context "when the names are correct" do
    its(:team_names) do
      is_expected.to include('Dogs')
      is_expected.to include('Cats')
    end
end

所以在我的测试中,我正在测试 team_names 方法。在 before..end 中,我模拟了对数据库的调用并期望它返回 team_1。如果我这样做,第一个测试用例会失败,但第二个会通过。这就说得通了。但我想模拟对 db 的两次调用并返回 teams 以便我可以测试我的方法是否返回两个团队的名称。我在测试文件中试过这个:

#....
before do
    allow(MyMongoGem::DB['teams']).to receive_message_chain(:find, :first)
      .with(any_args)
      .and_return team_1
   allow(MyMongoGem::DB['teams']).to receive_message_chain(:find, :first)
      .with(any_args)
      .and_return team_2

    subject.deliver!
  end
#.....
end

但是第二个调用覆盖了第一个。现在第一个测试用例将通过,但第二个测试用例将失败。输出将是 ['Dogs', 'Dogs'] 而不是 [Cats', 'Dogs']

谢谢!

最佳答案

您可以在 stub 方法时提供自己的 block ,如下所示:

allow(MyMongoGem::DB['teams']).to receive_message_chain(:find, :first) do |_|
    team_names.pop
end

其中 team_names 是您需要的团队名称列表,team_names = %w[Cats Dogs],顺序任意(请注意 team_names.pop 返回列表中的最后一个元素,而 team_names.shift 返回第一个)

关于ruby - 如何使用不同的参数模拟同一个数据库调用两次并将所有响应值与值数组进行匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57917323/

相关文章:

java - 为什么有时在 Maven 中测试期间 public static AtomicBoolean 变量为 false?

python - 'TableIterator' 对象没有属性 'shape'

ruby - 将格式作为参数传递给 rake spec

ruby-on-rails - 延迟加载 image_tag Rails

ruby-on-rails - 复制带有回形针附件的记录

java - 究竟什么是集成测试 - 与单元相比

ruby-on-rails - rspec 测试 ajax 响应(应该呈现部分)

ruby-on-rails - 应该 helper 不工作

ruby - 如何从 Rails 中的代码解析和发送整个复杂的 XML

ruby - 使用 "each do"输出一个列表,如何跳过最后一个逗号?