0

The following is the app/models/websites.rb

class Masterpiece < ActiveRecord::Base
    validates_presence_of :title, :link
    validates_uri_existence_of :link, :allow_redirect => false
end

The second validation is from the plugin Validates Existence of URI plugin

The following is the features/support/mocha.rb file

require 'mocha'
World(Mocha::API)

Before do
  mocha_setup
  @http_mock = mock('Net::HTTPResponse')
  @http_mock.stubs(:code => '200', :message => "OK", :content_type => "text/html", :body => '<title>Test</title><body>Body of the page</body>')
  Net::HTTP.expects(:get_response).returns(@http_mock)
  #Website.expects(:validates_uri_existence_of).returns(true)
end

After do
  begin
    mocha_verify
  ensure
    mocha_teardown
  end
end

But when I try to run a cucumber feature, it will try to create the record and before saving the above plugin will try to check over the Net to get the response. Its fine.
But when I want to get it Mocked on test environment, I'm trying to use mocha.

How shall I write the code to mock the Net response or the class method validates_uri_existence_of to run the test smoothly??

millisami
  • 9,931
  • 15
  • 70
  • 112

2 Answers2

2

The mock needs to be of the right class. Try:

Net::HTTP.expects(:get_response).returns(Net::HTTPSuccess.allocate)

(Class#allocate instantiates a class without calling initialize)

cwninja
  • 9,550
  • 1
  • 29
  • 22
  • Well, I changed the support/mocha.rb file as you've suggested. Before do mocha_setup Net::HTTP.expects(:get_response).returns(Net::HTTPSuccess.allocate) end But now when I run the feature, the following error is shown! not all expectations were satisfied unsatisfied expectations: - expected exactly once, not yet invoked: Net::HTTP.get_response(any_parameters) (Mocha::ExpectationError) – millisami Oct 03 '09 at 07:51
  • No idea why it isn't being called. If it is intended to not always get called you should use `stubs` instead of expects (same job, does not cause a fail when not triggered). Sounds like the Fakeweb foo (as @Radar mentioned) is a much nicer solution. Mocking at a low level almost always causes headaches. – cwninja Oct 03 '09 at 19:00
  • Thank you. I settled it just for now by appending .at_most(4) at the end of the code and it worked. But still I'm not satisfied with this solution. I looked at the FakeWeb before plunging into Mocha but didn't find that line of code to replace the Mocha one. Can you give me that line of code to make this work using FakeWeb? – millisami Oct 07 '09 at 15:11
  • you sir, deserve a cookie! – Stefan Dec 10 '14 at 23:14
2

I'd recommend using Fakeweb for this, as it is perfect for it.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261