Best Webmock_ruby code snippet using WebMock.API.assert_requested
webhook_command_test.rb
Source:webhook_command_test.rb
...29 end30 end31 should "post to api" do32 # webmock doesn't pass body params on correctly :[33 assert_requested(:post, @api,34 :times => 1)35 assert_requested(:post, @api,36 :headers => { 'Authorization' => 'key' })37 end38 end39 context "adding a global hook" do40 setup do41 stub_api_key("key")42 stub_request(:post, @api).to_return(:body => "Success!")43 @command.handle_options(["-g", "-a", @url])44 @command.execute45 end46 should "say hook was added" do47 assert_received(@command) do |command|48 command.say("Adding webhook...")49 command.say("Success!")50 end51 end52 should "post to api" do53 # webmock doesn't pass body params on correctly :[54 assert_requested(:post, @api,55 :times => 1)56 assert_requested(:post, @api,57 :headers => { 'Authorization' => 'key' })58 end59 end60 context "listing hooks with some available" do61 setup do62 stub_api_key("key")63 stub_request(:get, "#{@api}.yaml").to_return :body => <<EOF64---65foo:66- url: http://foogemhook.com67 failure_count: 068all gems:69- url: http://allgemshook.com70 failure_count: 071EOF72 end73 should "list all hooks" do74 @command.handle_options([])75 @command.execute76 assert_said(@command, "all gems:")77 assert_said(@command, "- http://allgemshook.com")78 assert_said(@command, "foo:")79 assert_said(@command, "- http://foogemhook.com")80 end81 should "list only specific hooks" do82 @command.handle_options(['foo'])83 @command.execute84 assert_said(@command, "foo:")85 assert_said(@command, "- http://foogemhook.com")86 assert_never_said(@command, "all gems:")87 assert_never_said(@command, "- http://allgemshook.com")88 end89 should "list only global hooks" do90 @command.handle_options(['-g'])91 @command.execute92 assert_said(@command, "all gems:")93 assert_said(@command, "- http://allgemshook.com")94 assert_never_said(@command, "foo:")95 assert_never_said(@command, "- http://foogemhook.com")96 end97 should "send get to api" do98 @command.handle_options([])99 @command.execute100 # webmock doesn't pass body params on correctly :[101 assert_requested(:get, "#{@api}.yaml",102 :times => 1)103 assert_requested(:get, "#{@api}.yaml",104 :headers => { 'Authorization' => 'key' })105 end106 end107 context "listing hooks with none available" do108 setup do109 stub_api_key("key")110 stub_request(:get, "#{@api}.yaml").to_return(:body => "{}")111 @command.handle_options([])112 @command.execute113 end114 should "list hooks" do115 assert_received(@command) do |command|116 command.say("You haven't added any webhooks yet.")117 end118 end119 end120 context "listing hooks with a json error" do121 setup do122 stub(@command).terminate_interaction123 stub_api_key("key")124 stub_request(:get, "#{@api}.yaml").to_return(:body => "fubar")125 @command.handle_options([])126 @command.execute127 end128 should "dump out with error message" do129 assert_received(@command) do |command|130 command.say("There was a problem parsing the data:")131 end132 end133 should "terminate interaction" do134 assert_received(@command) do |command|135 command.terminate_interaction136 end137 end138 end139 context "removing specific hooks" do140 setup do141 stub_api_key("key")142 stub_request(:delete, "#{@api}/remove").to_return(:body => "Success!")143 @command.handle_options([@gem, "-r", @url])144 @command.execute145 end146 should "say hook was removed" do147 assert_received(@command) do |command|148 command.say("Removing webhook...")149 command.say("Success!")150 end151 end152 should "send delete to api" do153 # webmock doesn't pass body params on correctly :[154 assert_requested(:delete, "#{@api}/remove",155 :times => 1)156 assert_requested(:delete, "#{@api}/remove",157 :headers => { 'Authorization' => 'key' })158 end159 end160 context "removing global hooks" do161 setup do162 stub_api_key("key")163 stub_request(:delete, "#{@api}/remove").to_return(:body => "Success!")164 @command.handle_options(["-g", "-r", @url])165 @command.execute166 end167 should "say hook was removed" do168 assert_received(@command) do |command|169 command.say("Removing webhook...")170 command.say("Success!")171 end172 end173 should "send delete to api" do174 # webmock doesn't pass body params on correctly :[175 assert_requested(:delete, "#{@api}/remove",176 :times => 1)177 assert_requested(:delete, "#{@api}/remove",178 :headers => { 'Authorization' => 'key' })179 end180 end181 context "test firing hooks" do182 setup do183 stub_api_key("key")184 stub_request(:post, "#{@api}/fire").to_return(:body => "Success!")185 @command.handle_options([@gem, "-f", @url])186 @command.execute187 end188 should "say hook was fired" do189 assert_received(@command) do |command|190 command.say("Test firing webhook...")191 command.say("Success!")192 end193 end194 should "send post to api" do195 # webmock doesn't pass body params on correctly :[196 assert_requested(:post, "#{@api}/fire",197 :times => 1)198 assert_requested(:post, "#{@api}/fire",199 :headers => { 'Authorization' => 'key' })200 end201 end202 end203end...
chapters_controller_test.rb
Source:chapters_controller_test.rb
...9 unstub_current_user10 get :show, params: { id: 1 }11 assert_response :ok, response.body12 assert_equal chapter.to_json, response.body13 WebMock.assert_requested(:get, "#{@controller.base_path}/1")14 end15 test 'get empty list of chapters' do16 WebMock.stub_request(:get, "#{@controller.base_path}").to_return(body: '[]')17 get :index18 assert_response :ok, response.body19 json = JSON.parse(response.body)20 assert_equal [], json21 end22 test 'get empty list of chapters without wisdom api request for missing config' do23 AreaChapterConfig.delete_all24 get :index25 assert_response :ok, response.body26 json = JSON.parse(response.body)27 assert_equal [], json28 end29 test 'get area filtered list of chapters' do30 api_reponse = '[{"id":1,"title":"new chapter","content":"<p>test</p>","order":1,"createdAt":"2018-01-10T10:17:04.000Z","updatedAt":"2018-01-10T16:17:42.000Z"}]'31 WebMock.stub_request(:get, "#{@controller.base_path}?ids=1,2,3").to_return(body: api_reponse)32 create_dummy_chapter_configuration33 get :index34 assert_response :ok, response.body35 assert_equal api_reponse, response.body36 WebMock.assert_requested(:get, "#{@controller.base_path}?ids=1,2,3")37 end38 test 'create chapter' do39 WebMock.stub_request(:post, "#{@controller.base_path}").to_return(status: 201, body: chapter.to_json)40 assert_difference -> { ChapterConfig.count } do41 assert_difference -> { AreaChapterConfig.count } do42 post :create, params: chapter.except(:id)43 assert_response :created, response.body44 assert_equal chapter.to_json, response.body45 end46 end47 WebMock.assert_requested(:post, "#{@controller.base_path}")48 end49 test 'handle error response on chapter create' do50 WebMock.stub_request(:post, "#{@controller.base_path}").to_return(status: 500, body: 'error')51 assert_no_difference -> { ChapterConfig.count } do52 assert_no_difference -> { AreaChapterConfig.count } do53 post :create, params: chapter.except(:id)54 assert_response :unprocessable_entity55 assert response.body.blank?56 end57 end58 WebMock.assert_requested(:post, "#{@controller.base_path}")59 end60 test 'update chapter' do61 chapter_config = ChapterConfig.create!(chapter_id: chapter[:id])62 area_chapter_config = AreaChapterConfig.create!(area: @user.area, chapter_config_id: chapter_config.id)63 WebMock.stub_request(:patch, "#{@controller.base_path}/#{chapter[:id]}").64 to_return(status: 200, body: chapter.to_json)65 assert_no_difference -> { ChapterConfig.count } do66 assert_no_difference -> { AreaChapterConfig.count } do67 patch :update, params: chapter68 assert_response :ok, response.body69 assert_equal chapter.to_json, response.body70 end71 end72 WebMock.assert_requested(:patch, "#{@controller.base_path}/#{chapter[:id]}")73 end74 test 'handle error response on chapter update' do75 WebMock.stub_request(:patch, "#{@controller.base_path}/#{chapter[:id]}").76 to_return(status: 500, body: 'error')77 assert_no_difference -> { ChapterConfig.count } do78 assert_no_difference -> { AreaChapterConfig.count } do79 patch :update, params: chapter80 assert_response :unprocessable_entity81 assert response.body.blank?82 end83 end84 WebMock.assert_requested(:patch, "#{@controller.base_path}/#{chapter[:id]}")85 end86 test 'destroy chapter' do87 WebMock.stub_request(:delete, "#{@controller.base_path}/#{chapter[:id]}").to_return(status: 204, body: '')88 chapter_config = ChapterConfig.create!(chapter_id: chapter[:id], active: true)89 area_chapter_config = AreaChapterConfig.create!(area: @user.area, chapter_config_id: chapter_config.id)90 assert_difference -> { ChapterConfig.count }, -1 do91 assert_difference -> { AreaChapterConfig.count }, -1 do92 delete :destroy, params: chapter.slice(:id)93 assert_response 204, response.body94 assert response.body.blank?95 end96 end97 WebMock.assert_requested(:delete, "#{@controller.base_path}/#{chapter[:id]}")98 end99 test 'handle error response on chapter destroy' do100 WebMock.stub_request(:delete, "#{@controller.base_path}/#{chapter[:id]}").101 to_return(status: 500, body: 'error')102 chapter_config = ChapterConfig.create!(chapter_id: chapter[:id], active: true)103 area_chapter_config = AreaChapterConfig.create!(area: @user.area, chapter_config_id: chapter_config.id)104 assert_no_difference -> { ChapterConfig.count } do105 assert_no_difference -> { AreaChapterConfig.count } do106 delete :destroy, params: chapter.slice(:id)107 assert_response :unprocessable_entity108 assert response.body.blank?109 end110 end111 WebMock.assert_requested(:delete, "#{@controller.base_path}/#{chapter[:id]}")112 end113 private114 def chapter115 {116 id: 1,117 title: 'dummy chapter',118 content: '<html></html>',119 order: 1120 }121 end122 def create_dummy_chapter_configuration123 c1 = ChapterConfig.create!(chapter_id: 1, active: true)124 c2 = ChapterConfig.create!(chapter_id: 2, active: true)125 c3 = ChapterConfig.create!(chapter_id: 3, active: true)...
persistance_test.rb
Source:persistance_test.rb
...44 body: {name: 'Armada Uno', errors: {name: 'is required'}}.to_json45 )46 fleet = Fleet.create()47 assert_equal ["is required"], fleet.errors[:name]48 assert_requested req_stub49 end50 test '#create' do51 req_stub = webmock(:post, "/fleets").with(52 body: { fleet: {name: 'Armada Uno'} }.to_json53 ).to_return(54 body: {id: 1, name: 'Armada Uno'}.to_json55 )56 Fleet.create(name: 'Armada Uno')57 assert_requested req_stub58 end59 test '#save w/o changes does not trigger a request' do60 webmock(:get, '/fleets', where: {id: 1}, limit: 1).to_return(61 body: [{id: 1, name: 'Armada Duo'}].to_json62 )63 fleet = Fleet.find(1)64 fleet.save65 assert fleet.save66 assert_equal 1, fleet.id67 assert_equal 'Armada Duo', fleet.name68 69 70 webmock(:get, '/sailors', where: {id: 1}, limit: 1).to_return(71 body: [{id: 1, name: 'Nandor', assignment: 'stay alert'}].to_json72 )73 fleet = Sailor.find(1)74 fleet.save75 assert fleet.save76 assert_equal 1, fleet.id77 assert_equal 'stay alert', fleet.assignment78 end79 test '#save attempts another request while in transaction' do80 webmock(:get, '/test_model_cs/schema').to_return(81 body: {82 attributes: {83 id: {type: 'integer', primary_key: true, null: false, array: false},84 name: {type: 'string', primary_key: false, null: true, array: false}85 }86 }.to_json,87 headers: { 'StandardAPI-Version' => '6.0.0.29' }88 )89 webmock(:get, '/test_model_bs/schema').to_return(90 body: {91 columns: {92 id: {type: 'integer', primary_key: true, null: false, array: false},93 name: {type: 'string', primary_key: false, null: true, array: false}94 }95 }.to_json,96 headers: { 'StandardAPI-Version' => '5.0.0.5' }97 )98 webmock(:get, '/test_model_as/schema').to_return(99 body: {100 columns: {101 id: {type: 'integer', primary_key: true, null: false, array: false},102 name: {type: 'string', primary_key: false, null: true, array: false}103 }104 }.to_json,105 headers: { 'StandardAPI-Version' => '5.0.0.5' }106 )107 assert_raises ActiveRecord::StatementInvalid do108 TestModelB.create109 end110 end111 test '#update clears belongs_to relationship' do112 webmock(:get, "/ships", where: {id: 1}, limit: 1).to_return(113 body: [{id: 1, fleet_id: 1, name: 'Armada Uno'}].to_json114 )115 req_stub = webmock(:patch, '/ships/1').with(116 body: {ship: {fleet_id: nil}}.to_json117 ).to_return(118 body: {id: 1, name: 'Armada Uno'}.to_json119 )120 ship = Ship.find(1)121 assert ship.update(fleet: nil)122 assert_requested req_stub123 end124 test '#update' do125 webmock(:get, "/ships", where: {id: 1}, limit: 1).to_return(126 body: [{id: 1, fleet_id: nil, name: 'Armada Uno'}].to_json127 )128 req_stub = webmock(:patch, "/ships").with(129 body: { ship: { name: 'Armada Trio' } }.to_json130 ).to_return(131 body: {id: 1, name: 'Armada Trio'}.to_json132 )133 Ship.find(1).update(name: 'Armada Trio')134 assert_requested req_stub135 end136 test '#update!' do137 webmock(:get, "/ships", where: {id: 1}, limit: 1).to_return(138 body: [{id: 1, fleet_id: nil, name: 'Armada Uno'}].to_json139 )140 req_stub = webmock(:patch, "/ships").with(141 body: { ship: { name: 'Armada Trio' } }.to_json142 ).to_return(143 body: {id: 1, name: 'Armada Trio'}.to_json144 )145 Ship.find(1).update!(name: 'Armada Trio')146 assert_requested req_stub147 end148end...
assert_requested
Using AI Code Generation
1 to_return(:status => 200, :body => "Hello world!", :headers => {})2response = Net::HTTP.get_response(URI.parse("http://example.com/"))3assert_requested(:get, "http://example.com/", :times => 1)4 to_return(:status => 200, :body => "Hello world!", :headers => {})5response = Net::HTTP.get_response(URI.parse("http://example.com/"))6assert_requested(:get, "http://example.com/", :times => 1)7 to_return(:status => 200, :body => "Hello world!", :headers => {})8response = Net::HTTP.get_response(URI.parse("http://example.com/"))9assert_requested(:get, "http://example.com/", :times => 1)
assert_requested
Using AI Code Generation
1 to_return(:status => 200, :body => "Hello World", :headers => {})2response = HTTParty.get('http://example.com/')3assert_requested(:get, "http://example.com/", :times => 1)4 to_return(:status => 200, :body => "Hello World", :headers => {})5response = HTTParty.get('http://example.com/')6assert_not_requested(:get, "http://example.com/", :times => 1)
assert_requested
Using AI Code Generation
1 to_return(:status => 200, :body => "", :headers => {})2Net::HTTP.get_response(URI('http://www.example.com/'))3 to_return(:status => 200, :body => "", :headers => {})4Net::HTTP.get_response(URI('http://www.example.com/'))5 to_return(:status => 200, :body => "", :headers => {})6Net::HTTP.get_response(URI('http://www.example.com/'))
assert_requested
Using AI Code Generation
1 to_return(:status => 200, :body => "stubbed response", :headers => {})2 response = Net::HTTP.get_response(URI('http://www.google.com'))3 assert_requested(:get, 'http://www.google.com', :times => 1)4 to_return(:status => 200, :body => "stubbed response", :headers => {})5 response = Net::HTTP.get_response(URI('http://www.google.com'))6 assert_requested(:get, 'http://www.google.com', :times => 2)
assert_requested
Using AI Code Generation
1 stub_request(:get, 'http://google.com/').to_return(body: 'Hello World')2 request = Net::HTTP.get('google.com', '/')3 assert_requested(:get, 'http://google.com/')4 Failure/Error: assert_requested(:get, 'http://google.com/')5 Real HTTP connections are disabled. Unregistered request: GET http://google.com/ with headers {}6Finished in 0.00587 seconds (files took 0.1837 seconds to load)7 should make a request to google (FAILED - 1)8 Failure/Error: assert_requested(:get, 'http://google.com/')9 Real HTTP connections are disabled. Unregistered request: GET http://google.com/ with headers {}10Finished in 0.00588 seconds (files took 0.1836 seconds to load)11 Failure/Error: assert_requested(:get, 'http://google.com/')12 Real HTTP connections are disabled. Unregistered request: GET http://google.com/ with headers {}13Finished in 0.00587 seconds (files took 0.1839 seconds to load)
assert_requested
Using AI Code Generation
1 stub_request(:post, "http://localhost:8080/").to_return(status: 200, body: "hello", headers: {})2 RestClient.post("http://localhost:8080/", :body => { :test => "test" }.to_json, :content_type => :json)3 assert_requested(:post, "http://localhost:8080/")4 stub_request(:post, "http://localhost:8080/").to_return(status: 200, body: "hello", headers: {})5 RestClient.post("http://localhost:8080/", :body => { :test => "test" }.to_json, :content_type => :json)6 assert_requested(:post, "http://localhost:8080/")7 stub_request(:post, "http://localhost:8080/").to_return(status: 200, body: "hello", headers: {})8 RestClient.post("http://localhost:8080/", :body => { :test => "test" }.to_json, :content_type => :json)9 assert_requested(:post, "http://localhost:8080/")10 stub_request(:post, "http://localhost:8080/").to_return(status: 200, body
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!