ruby-on-rails - 为什么无法向该对象添加 RSpec stub 方法?

标签 ruby-on-rails rspec rspec-rails

出于某种原因,RSpec stub 在我的测试中不可用,我不明白为什么。

这是一个示例测试:

RSpec.describe User, type: :model do 
  it "Should allow me to stub a model" do
    u = User.new
    u.stub(:test)
    u.test
  end
end

这是测试结果:

Failures:

  1) Subscription Should allow me to stub a model
     Failure/Error: u.stub(:test)
     NoMethodError:
       undefined method `stub' for #<User:0x007fa5cfea20c8>
     # ./spec/models/user_spec.rb:6:in `block (2 levels) 
     in <top (required)>'

FWIW 我的规范帮助程序文件的模拟配置部分如下:

config.mock_with :rspec do |mocks|
  # Enable only the newer, non-monkey-patching expect syntax.
  # For more details, see:
  #   - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
  mocks.syntax = :expect

  # Prevents you from mocking or stubbing a method that does not exist on
  # a real object. This is generally recommended.
  mocks.verify_partial_doubles = true
end

最佳答案

旧语法是 accessible with mocks.syntax = :should 。但是,您可以使用新的:allow(u).to receive(:test)

关于ruby-on-rails - 为什么无法向该对象添加 RSpec stub 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25566514/

相关文章:

ruby-on-rails - 如何在 IRB 的两个数组中找到匹配项?

ruby-on-rails - Rails 助手不在测试环境中工作

ruby-on-rails - rails rspec 在测试时访问其他表

RSpec - 如何在所有请求测试中全局设置 https 协议(protocol)

ruby-on-rails - Rails 3.1 插件 gem、虚拟测试应用程序、rspec

ruby-on-rails - 为什么 before_action :authorize fail with 'wrong number of arguments' ?

ruby-on-rails - 通过RSpec发送自定义 header

html - RoR - 如何将一些带有 css 的 HTML 元素转换为 Rails

ruby - 第一次在 ruby​​ 中使用 rspec 进行单元测试

ruby-on-rails - rails 中的单元测试 - 带回形针的模型