【问题标题】:How do I expect a method to be run with specific ActiveRecord parameters我如何期望使用特定的 ActiveRecord 参数运行方法
【发布时间】:2017-10-23 15:12:58
【问题描述】:

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

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

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

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

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

有更好的方法吗?

【问题讨论】:

    标签: ruby-on-rails unit-testing activerecord ruby-mocha


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      Sergio 给出了最好的答案,我接受了。我独立发现了答案,并在此过程中发现我需要从 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
      

      【讨论】:

        【解决方案3】:

        您可以使用 RSpec custom matcher 并比较该函数中的预期值。

        【讨论】:

          猜你喜欢
          • 2013-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-12
          • 2016-05-23
          • 1970-01-01
          • 2013-07-24
          • 2018-05-05
          相关资源
          最近更新 更多