摩卡+ Cucumber 来嘲笑 Net 的回应

发布于 2024-08-06 16:58:11 字数 1197 浏览 1 评论 0原文

以下是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤寂小茶 2024-08-13 16:58:11

模拟必须属于正确的类别。尝试:(

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

Class#allocate实例化一个类而不调用initialize)

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)

小忆控 2024-08-13 16:58:11

我建议使用 Fakeweb 来实现此目的,因为它非常适合。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文