Reputation: 306
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!
Upvotes: 0
Views: 555
Reputation: 101976
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.
Upvotes: 1