我如何期望使用特定的活动记录参数运行方法



在 Rails 4.2 上使用 Mocha。我正在测试一个方法,它应该使用正确的参数调用另一个方法。这些参数是它从数据库调用的 ActiveRecord 对象。这是我测试中的关键行:

UserMailer.expects(:prompt_champion).with(users(:emma), [[language, 31.days.ago]]).once

users(:emma)language 都是 ActiveRecord 对象。

即使进行了正确的调用,测试也会失败,因为参数与预期不匹配。我认为这可能是因为每次从数据库中提取记录时,它都是一个不同的 Ruby 对象。

我认为解决方法之一是查看我的代码中使用了什么方法来提取记录并存根该方法以返回模拟,但我不想这样做,因为检索了一大堆记录然后过滤下来得到正确的记录,模拟所有这些记录会使测试方式过于复杂。

有没有更好的方法

您可以使用允许/期望的块形式。

expect(UserMailer).to receive(:prompt_champion) do |user, date|
  expect(user.name).to eq "Emma"
  expect(date).to eq 31.days.ago # or whatever
end

塞尔吉奥给出了最好的答案,我接受了。我独立发现了答案,并在此过程中发现我需要从ActionMailer方法返回模拟以使一切正常工作。

我认为最好在这里发布我的完整测试,以便任何其他倒霉的冒险家以这种方式来。我正在使用Minitest-Spec。

it 'prompts champions when there have been no edits for over a month' do
    language.updated_at = 31.days.ago
    language.champion = users(:emma)
    language.save
    mail = mock()
    mail.stubs(:deliver_now).returns(true)
    UserMailer.expects(:prompt_champion).with do |user, languages|
        _(user.id).must_equal language.champion_id
        _(languages.first.first.id).must_equal language.id
    end.once.returns(mail)
    Language.prompt_champions
end

您可以使用 RSpec 自定义匹配器并比较该函数中的预期值。

最新更新