在尝试在Rails上进行API请求存根时出现问题。

huangapple go评论67阅读模式
英文:

Problem when trying to stub API requests on Rails

问题

我正在尝试使用Webmock来存根(API request)。而不是从我的Rails控制器获取"真实"数据,我想返回虚假数据,仅用于测试目的。

我有一个带有按钮的React前端,该按钮获取我的API端点:

const handleClick = async () => {
    const response = await fetch("api_endpoint");
    const data = await response.json();
    console.log("data: ", JSON.stringify(data));
};

这是我的测试文件:

require 'rails_helper'
require 'spec_helper'

RSpec.describe 'visiting the embedded app', type: :system do
  it 'visits the embedded app' do
    stub_request(:get, 'api_endpoint').to_return(
      body: { data: 'dummy' }.to_json
    )

    visit 'my react page with the button'
    click_button "Call API"
    sleep 10
    random_assert
  end
end

我没有得到"data: dummy",而是从我的Rails控制器中获取了"真实"数据。

这个实现有什么问题?如果需要更多信息,请告诉我!

英文:

I'm trying to stub an API request using Webmock. Instead of getting the "real" data from my Rails controller, I want to return dummy data, for test purposes only.

I have a React frontend with a button that fetches my api endpoint:

const handleClick = async () => {
    const response = await fetch("api_endpoint");
    const data = await response.json();
    console.log("data: ", JSON.stringify(data));
  };

This is my test file:

require 'rails_helper'
require 'spec_helper'

RSpec.describe 'visiting the embedded app', type: :system do
  it 'visits the embedded app' do
    stub_request(:get, 'api_endpoint').to_return(
      body: { data: 'dummy' }.to_json
    )

    visit 'my react page with the button'
    click_button "Call API"
    sleep 10
    random_assert
  end
end

Instead of getting data: dummy, I get the "real" data from by rails controller.

What is wrong with this implementation? Tell me if you need more information!

答案1

得分: 1

你基本上误解了测试中的HTTP存根化是如何工作的。WebMock 用于存根化从您的服务器发送到其他服务器的HTTP请求。

我假设这是WebMock,但同样适用于几乎任何其他服务器端HTTP存根化工具。

它不会存根化从客户端发送的请求 - 因为这段代码甚至不在客户端运行。这是由像Mirage JS这样在客户端运行的JavaScript库完成的,或者通过将请求发送到服务器上返回虚拟数据而不是实际实现的端点。

英文:

You have fundamentially missunderstood how HTTP stubbing in tests works. WebMock is used to stub HTTP requests sent from your server to other servers.

I'm assuming this is WebMock but the same applies to pretty much any other server side HTTP stubbing tool.

It does not stub requests sent from the client - simply becuase this code isn't even running in the client. That is done with javascript libraries like Mirage JS running in the client or by sending the requests to endpoints on the server that return dummy data instead of the actual implementation.

huangapple
  • 本文由 发表于 2023年2月8日 23:29:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定