直接在模型上调用rspec导致存根中的错误!方法

时间:2011-01-29 10:57:37

标签: ruby-on-rails ruby rspec

运行时:

rake spec:models

一切运作良好,但是当我做的时候

rspec spec/models/spot_spec.rb

Spot.stub! :test1,我得到:

undefined method `stub!' for Spot:Class

只有当我包含该存根时才会发生错误!线。

任何想法如何避免它?我想仅为特定型号运行规格。

更新

使用Ruby 1.9.2和RSpec 2.4.0,这里是spot_spec.rb代码:

require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Spot do
  before(:all) do
    Spot.stub! :test1
    @spot = Spot.new
  end

  subject {@spot}

  describe "validations" do
    it { should validate_presence_of(:user) }
  end
end

spec_helper.rb:

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec
end

2 个答案:

答案 0 :(得分:14)

before(:all)电话中原来是issue

  

这是对的。模拟是含蓄的   (:每个)验证并清除   所以他们以前不会工作(:全部)。

将其更改为before(:each)解决了它。

谢谢大家。

答案 1 :(得分:1)

让spot_spec.rb包含spec_helper.rb,然后确保spec_helper.rb包含spot_spec.rb。

如果您运行的是ruby 1.9+,则可以使用require_relative在spec_helper.rb中包含spot_spec.rb

更新

在spec_helper.rb中添加:

require_relative '../app/models/spot'