我有一个控制器,它有post_review
动作调用Rest Client API调用。
def post_review
...
headers = { "CONTENT_TYPE" => "application/json",
"X_AUTH_SIG" => Rails.application.secrets[:platform_receiver_url][:token] }
rest_client.execute(:method => :put,
:url => Rails.application.secrets[:platform_receiver_url][:base_url] + response_body["application_id"].to_s,
:content_type => :json,
:payload => response_body.to_json,
:headers => headers)
document_manual_result(response_body)
delete_relavent_review_queue(params[:review_queue_id])
...
end
document_manual_result
是一种日志记录方法,delete_relavent_review_queue
是一种回调类型方法,它将删除该项目。
我已经编写了几个测试post_review操作的副作用的测试,即它记录了我发送结果(又名:response_body
)并删除了另一个对象。
describe "Approved#When manual decision is made" do
it "should delete the review queue object" do
e = Event.create!(application_id: @review_queue_application.id)
login_user @account
post :post_review, @params
expect{ReviewQueueApplication.find(@review_queue_application.id)}.to raise_exception(ActiveRecord::RecordNotFound)
end
it "should update the event created for the application" do
e = Event.create!(application_id: @review_queue_application.id)
login_user @account
post :post_review, @params
expect(Event.find(e.id).manual_result).to eq(@manual_result)
end
end
在我打开RestClient
之前,测试工作正常,但现在休息客户端正在执行它正在破坏规范。 我想仅存储控制器操作的rest_client.execute
部分,因此我可以测试该方法的其他副作用。我指向的网址是localhost:3001
所以我试过了:
stub_request(:any, "localhost:3001")
我在其中使用了它,我之前的块没有做任何事情,我在实际测试 it 块中尝试了它,就在我post :post_review, @params
之前Webmock似乎什么都不做。我认为webmock所做的是,它正在监听对特定URL的任何请求,并且它默认返回成功或您指定的选项块。我不确定我是否正确使用它。
答案 0 :(得分:2)
在此片段中:
stub_request(:any, "localhost:3001")
:any
指的是像GET或POST一样调用的http方法。因此,您正在使用GET / POST /来确定该URL的唯一内容以及该URL。我的猜测是你发送请求的不完全是localhost:3001
。
尝试将Rails.application.secrets[:platform_receiver_url][:base_url] + response_body["application_id"].to_s
解压缩到变量中,并在运行规范时将其记录下来。我的猜测是你需要将你的存根更改为该URL,这可能类似于localhost:3001 / some_resource / 1.
要存储localhost上的所有路径:3001
Webmock还支持通过正则表达式匹配网址:
stub_request(:any, /localhost:3001*/)