views:

440

answers:

2

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??

A: 

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
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)endBut 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
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
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
+1  A: 

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

Ryan Bigg
+1. I was trying to remember what this was called for my answer.
cwninja