繁体   English   中英

预期 Ruby 规范:1 次收到任何参数:0 次收到任何参数

[英]Ruby spec expected: 1 time with any arguments received: 0 times with any arguments

运行我的规范时出错,我猜测可能是 update_all 已被弃用。 我一定是遗漏了一些明显的东西

代码:

def update_the_members_email
    self.the_members.update_all(email: self.email)
end

规格:

describe 'update_the_members_email' do

    describe 'when after_save is triggered' do
       let(:updated_email) { Faker::Internet.safe_email }
        before do
          user.email = updated_email
          user.save
        end
      it 'triggers update_all' do
        expect(user).to receive_message_chain(:the_members, :update_all).with({ :email => updated_email })
      end
    end
  end
end

错误:

`1) 当 after_save 被触发时用户 update_the_members_email 触发 update_all 失败/错误:expect(user).to receive_message_chain(:the_members, :update_all).with({:email => new_email })

  [....].the_members(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

`

我试过使用 update_column 而不是 update_all。 尝试了其他几种方法来说明这一点。 花了很多时间研究。

假设update_the_members_email由保存后回调调用...

必须在调用之前设置模拟 before发生测试之前。 所以user.email发生您设定期望之前。 期望永远不会看到它。

describe 'after save callbacks' do
  it 'updates all members email when the email is updated' do
    updated_email = Faker::Internet.safe_email

    expect(user).to receive_message_chain(:the_members, :update_all)
      .with(email: updated_email )

    user.update!(email: updated_email)
  end
end

请注意,这里不需要模拟。 只要确保用户有一些成员并直接测试即可。

describe 'after save callbacks' do
  let(:updated_email) { Faker::Internet.safe_email }

  context 'when the user email is updated' do
    before do
      user.update!(email: updated_email)
    end

    it 'updates all members email when the email is updated' do
      # I'm assuming the user has members.
      expect(user.the_members).to all have_attributes(email: updated_email)
    end
  end
end

  • 无需将 self 附加到方法调用。 the_members.update_all(email: email)
  • 使用 Ruby 2.0 风格传递命名参数: with(email: updated_email)
  • 试试rubocoprubocop-rspec告诉你好的风格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM