为什么不能将RSpec存根方法添加到此对象中?

时间:2014-08-29 10:32:33

标签: ruby-on-rails rspec rspec-rails

由于某些原因,我的测试中没有RSpec存根,我无法弄清楚原因。

以下是一个示例测试:

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

1 个答案:

答案 0 :(得分:3)

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