[英]Rspec: how to test Service Object method “call” which is called in Controller action create?
Can somebody help me with rspec testing method call in Service Object?有人可以帮助我在服务 Object 中调用 rspec 测试方法吗?
class UserEntitiesController < ApplicationController
def create
@result = UserEntities::Create.new(params).call
return render '/422.json.jbuilder', status: :unprocessable_entity unless @result
end
here is the service objects:这是服务对象:
module UserEntities
class Create
attr_accessor :params
def initialize(params)
@params = params
end
def call
@user_entity = UserEntity.new(user_entity_params)
set_time
if @user_entity.save
@user_entity
else
error_result
end
end
private
def error_result
false
end
def user_entity_params
@params.require(:user_entity).permit(:information,
:destroy_option,
:reviews)
end
def set_time
if @params[:available_days].present?
@user_entity.termination = Time.now + @params[:available_days].days
end
end
end
end
I tried to find information how to do this, but there are not so many.我试图找到如何做到这一点的信息,但没有那么多。 Also i read some我也读了一些
You can certainly write a unit test to test the Service Object
standalone您当然可以编写一个单元测试来独立测试Service Object
In this case, create a file spec/services/user_entities/create_spec.rb
在这种情况下,创建一个文件spec/services/user_entities/create_spec.rb
describe UserEntities::Create do
let(:params) { #values go here }
context ".call" do
it "create users" do
UserEntities::Create.new(params).call
# more test code
end
# more tests
end
end
Later in the controller tests, if you are planning to write such, you do not need to test UserEntities::Create
instead you can just mock the service object to return the desired result稍后在 controller 测试中,如果您打算编写此类,则无需测试UserEntities::Create
相反,您可以模拟服务 object 以返回所需的结果
describe UserEntitiesController do
before do
# to mock service object in controller test
allow(UserEntities::Create).to receive(:new)
.and_return(double(:UserEntities, call: "Some Value"))
end
# controller tests go here
end
As a supplement to @bibin answer.作为@bibin 答案的补充。 If you want to mock some instance's method renturn:如果你想模拟某个实例的方法返回:
allow_any_instance_of(UserEntities::Create).to receive(:call).and_return("some value")
if you want to raise a eror:如果您想提出错误:
allow_any_instance_of(UserEntities::Create).to receive(:call).and_raise("boom")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.