简体   繁体   中英

RSpec: how to test that a static method is called but prevent it from actually running?

I have a static method that is doing HTTP POST to a remote server.

I want to test that this method is called with the correct arguments whenever its needed, but I also want to prevent it from actually running so it won't execute the actual HTTP request while testing.

how can I stub that method globally so I won't have to do it in every test case for preventing it from actually running ? and if doing so, how do I unstub it for the specific test case of testing the actual method ?

If you simply want to stub the method in all your specs and check that it receives the correct arguments whenever it is called (assuming they are the same in each case), you can just add a stub to your spec_helper in a before(:each) block:

RSpec.configure do |config|
  ...
  config.before(:each) do
    SomeClass.stub(:some_static_method).with(...).and_return(...)
  end
  ...
end

That will fail if the stub is called with anything but the arguments you specified. Note that you can also use should_receive as @appneadiving suggested, but you'll have to call it with any_number_of_times to make sure it doesn't fail if you don't call it, and that's basically the same as using a stub (see this discussion ).

Another route is to use the webmock gem to stub requests to a given URL. Using this approach you don't (necessarily) need to stub your method, you can just let it run as usual with the certainty that whenever it tries to access the server with the arguments you specify, it will get a given response.

To use the webmock throughout your specs you'll have to add a line in spec_helper like the one above, calling the stub_request method, eg:

stub_request(:any, "www.example.com").with(:query => { :a => "b"}).to_return(...)

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM