首页 > 解决方案 > 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

当我运行规范时,它总是显示产量错误,我需要产量才能使其工作,但我不确定如何专门修复规范

标签: ruby-on-railsrspec

解决方案


因为你没有在你的测试中通过一个块

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

推荐阅读