ruby - 如何编写使用 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
有人能告诉我我错过了什么吗
解决方案
我可能会先在这里查看您的代码。
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
如果没有找到它会自动返回。
从那里开始,然后像其他评论者一样,然后发布您的课程和规范,我们可以从那里开始。
推荐阅读
- playframework - 如何在 Play Framework 2.7 中获取当前语言
- sql - 为 ORACLE SQL 结果添加索引以使结果唯一
- javascript - 量角器找不到 h1 元素
- c# - WPF DesignInstace 导致将数据上下文的命名空间显示为字符串而不是绑定结果
- c# - c# 从另一个方法访问方法内部的变量
- typescript - 如何使用打字稿声明空对象数组的类型?
- google-apps-script - 将 lockservice 和 SpreadsheetApp.flush 添加到脚本(Google App Script / Google Sheets)
- .net-core - Cosmos DB Upsert 失败
- azure - 外部团队对 Azure Data Lake 的部分访问权限
- python - python shell的平台和架构之间的区别?