问题
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??
回答1:
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)
回答2:
I'd recommend using Fakeweb for this, as it is perfect for it.
来源:https://stackoverflow.com/questions/1510719/mocha-cucumber-to-mock-the-net-response