簡體   English   中英

rspec測試調用方法發送重新確認指令

[英]Rspec test call method send reconfirmation instruction

我正在使用 Rspec 來測試用戶更改密碼時的情況,將發送郵件。 我想檢查是否只發送了 1 封郵件。 我不想使用Action::Mailer.deliveries來檢查,而是想檢查是否調用了方法以及調用了多少。

在搜索時,我從 rspec mock 中找到了Test Spyhttps : //github.com/rspec/rspec-mocks#test-spies

describe 'PUT /email' do
  include_context 'a user has signed in', { email: 'old-email@example.com', password: 'correct_password' }

  context  'correct new email, correct password' do
    before do
      allow(user).to receive(:send_reconfirmation_instructions)
    end

    it do
      should == 302
      expect(user.reload.unconfirmed_email).to eq 'new-email@example.com'
      expect(user).to receive(:send_reconfirmation_instructions).once
    end
  end
end

但我得到了錯誤:

  Failure/Error: expect(user).to receive(:send_reconfirmation_instructions)

   (#<User id: 1269, email: “old-email@example.com”, created_at: “2019-08-27 03:54:33", updated_at: “2019-08-27 03:54:33”...“>).send_reconfirmation_instructions(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

send_reconfirmation_instructions這個函數來自send_reconfirmation_instructionshttps : //github.com/plataformatec/devise/blob/master/lib/devise/models/confirmable.rb#L124-L130

我做了binding.pry並且我確定這個函數內部的測試跳轉但是 rspec 仍然失敗。

編輯:我可以這樣寫:

describe 'PUT /email' do
  include_context 'a user has signed in', { email: 'old-email@example.com', password: 'correct_password' }

  context  'correct new email, correct password' do
    before do
      expect_any_instance_of(User).to receive(:send_reconfirmation_instructions).once
    end

    it do
      should == 302
      expect(user.reload.unconfirmed_email).to eq 'new-email@example.com'
      # expect(user).to receive(:send_reconfirmation_instructions).once
    end
  end
end

但是我遇到了另一個錯誤:

Failure/Error: 
(#<User user_id: 1418, email: “old-email@example.com”...“>).send_reconfirmation_instructions(#<User user_id: 1418, email: “old-email@example.com” ...“>)
                expected: 1 time with any arguments
                received: 2 times with arguments: (#<User user_id: 1418, email: “old-email@example.com”, id: 1323...“>)

您檢查用戶是否收到消息的行應為:

expect(user).to have_received(:send_reconfirmation_instructions).once

代替:

expect(user).to receive(:send_reconfirmation_instructions).once

前者你說expect(obj).to have_received(:msg)要求你斷言消息被調用,正如你打算做的那樣。

另一方面,后者,你說expect(obj).to receive(:msg)是一種在動作之前設置期望的方法,即代替allow(obj).to receive(:msg)無需斷言它是在操作之后調用的。 規范運行后,它會自動斷言它是否被調用。

這解釋了您在指定時遇到的錯誤

expect(user).to receive(:send_reconfirmation_instructions).once

因為在該行之后沒有代碼將該消息發送給user ,該消息在規范之后得到驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM