摩卡+ Cucumber 来嘲笑 Net 的回应
以下是 app/models/websites.rb
class Masterpiece < ActiveRecord::Base
validates_presence_of :title, :link
validates_uri_existence_of :link, :allow_redirect => false
end
第二次验证来自插件 Validates Existence URI 插件
以下是 features/support/mocha.rb 文件
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
但是当我尝试运行 Cucumber 功能时,它会尝试创建记录,并且在保存之前,上述插件会尝试通过网络检查得到回应。还好。
但是当我想在测试环境中模拟它时,我尝试使用摩卡。
我该如何编写代码来模拟网络响应或类方法 validates_uri_existence_of 顺利运行测试?
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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模拟必须属于正确的类别。尝试:(
Class#allocate
实例化一个类而不调用initialize)The mock needs to be of the right class. Try:
(
Class#allocate
instantiates a class without calling initialize)我建议使用 Fakeweb 来实现此目的,因为它非常适合。
I'd recommend using Fakeweb for this, as it is perfect for it.