首页 > 解决方案 > 如何编写使用 with 发送参数的方法模拟

问题描述

嗨,我想知道如何为以下内容编写 rspec

def find_user(content)
  user = User.find(content.to_i) || 
  User.find(email: content) rescue 
 nil
end

我试着写

It "user with user name" do
  expect(User).to receive(:find).with(email: "test@a.com").and_return(user)
End

但我gettig错误说

Argument Error
Block not Passed

有人能告诉我我错过了什么吗

标签: rubyrspecjrubyrspec-rails

解决方案


我可能会先在这里查看您的代码。

def find_user(content)
  user = User.find(content.to_i) || 
  User.find(email: content) rescue 
 nil
end

什么是内容?我看起来您期望的是 user_id 或电子邮件地址。

从控制台执行此操作:

irb(main):080:0> User.find("email@email.com".to_i)
=> ActiveRecord::RecordNotFound (Couldn't find User with 'id'=0)

因此,似乎拥有一个通用find_user方法可能会导致一些测试写作混乱。

很多时候,过于复杂的测试指向过于复杂的代码。

也许你需要一种方法

find_user_by_email(email)

和另一个 find_user_by_id(id)

另外,请参阅https://api.rubyonrails.org/v6.1.3.2/classes/ActiveRecord/FinderMethods.html#method-i-find_by

nil如果没有找到它会自动返回。

从那里开始,然后像其他评论者一样,然后发布您的课程和规范,我们可以从那里开始。


推荐阅读