ruby-on-rails - localjumperror 没有给出块(yield)
问题描述
当我运行我的规范时,它显示
localjumperror 没有给出块(yield)
我的服务文件
服务/update_many_post.rb
class UpdateManyPost
def call
posts.each do |post|
response = UpdateAPost.new(post: post).call
yield response
end
end
private
def posts
Post.all
end
end
/service/update_a_post.rb
class UpdateAPost
def initialize(post:)
@post = post
end
def call
@post.title = "I am great"
@post.save
end
end
这就是我所说的服务。
UpdateManyPost.new.call do |response|
puts(response)
end
我的 rspec 文件
describe 'call' do
let(:posts) { build(:post, 3) }
subject { UpdateManyPost.new }
it "has to update all the post" do
expect { subject.call }
end
end
当我运行规范时,它总是显示产量错误,我需要产量才能使其工作,但我不确定如何专门修复规范
解决方案
因为你没有在你的测试中通过一个块
expect { subject.call }
你会得到一个 yield 错误,因为没有什么可以屈服的。
您可以通过在该调用中传递一个块来解决这个问题,例如
expect { subject.call{|_|}}
或者您可以更改您的方法定义以选择性地调用该块
def call
posts.each do |post|
response = UpdateAPost.new(post: post).call
yield response if block_given?
end
end
这将检查是否为“调用”方法提供了一个块,并且仅在提供了一个块时才产生。
话虽如此,您的测试不会测试任何也会导致问题的东西,因为存在没有任何断言(匹配器)的期望。你想测试什么?
你可以测试为
subject.call do |resp|
expect(resp.saved_change_to_attribute?(:title)).to eq true
expect(resp.title).to eq("I am great")
end
或者
expect(Post.where.not(title: "I am great").exists?).to eq true
subject.call
expect(Post.where.not(title: "I am great").exists?).to eq false
推荐阅读
- php - 从扩展 Doctrine\DBAL\Connection 的类中的第二个数据库连接中获取数据
- android - 如何修复 ArrayAdapter 中的类型不匹配?
- flutter - Flutter 垂直可滚动抽屉
- docker - 如何在 chrome 中调试无头 pdf 打印问题?
- .net-core - .net core 短生命周期缓解
- javascript - 如何识别网页中是否存在滚动。还得到它的坐标吗?
- python - 用户输入给出“ValueError:int() 以 10 为基数的无效文字:”
- javascript - 会话存储上的元素“未定义”问题
- javascript - 如果转换持续 n 秒,是否可以在该时间的指定百分比处启动它?
- amazon-web-services - 复制没有表结构的 Redshift