0

我正在使用 Rails 3.1,我想在我的规范中添加一些存根和模拟,但我得到一个 NoMethodError:

undefined method `stub_model' for #<Class:0x007ff9c339bd80> (NoMethodError)

这是我的 GemFile 的摘录:

gem 'rspec'
gem 'rspec-rails'

我跑了 bundle install 和 rails g rspec:install

这是尝试创建 stub_model 的代码

  0     @flight = stub_model(Flight)
  1     Flight.stub! (:all).and_return([@flight])

这是spec_helper.rb:

  0 # This file is copied to spec/ when you run 'rails generate rspec:install'
  1 ENV["RAILS_ENV"] ||= 'test'
  2 require File.expand_path("../../config/environment", __FILE__)
  3 require 'rspec/rails'
  4 
  5 # Requires supporting ruby files with custom matchers and macros, etc,
  6 # in spec/support/ and its subdirectories.
  7 Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
  8   
  9 RSpec.configure do |config|
 10   # == Mock Framework
 11   #
 12   # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
 13   #
 14   # config.mock_with :mocha
 15   # config.mock_with :flexmock
 16   # config.mock_with :rr
 17   config.mock_with :rspec
 18 
 19   # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
 20   config.fixture_path = "#{::Rails.root}/spec/fixtures"
 21     
 22   # If you're not using ActiveRecord, or you'd prefer not to run each of your
 23   # examples within a transaction, remove the following line or assign false
 24   # instead of true.
 25   config.use_transactional_fixtures = true
 26 end 

我正在调用“rspec ./spec”和“bundle exec rspec ./spec”(两者都试过,没有区别)

我所做的一切似乎都是教科书(事实上,我正在遵循 The Rails 3 Way)。

我错过了什么?

4

2 回答 2

2

您的原始代码可能在规范示例之外运行。这将给出您描述的错误:

class Foo; end
describe Foo do
  @foo = stub_model(Foo)
  Foo.stub!(:all).and_return([@foo])
end

但这会起作用:

class Foo; end
describe Foo do
  before do
    @foo = stub_model(Foo)
    Foo.stub!(:all).and_return([@foo])
  end
end
于 2012-03-15T10:38:17.877 回答
0

请参阅原始问题中的评论。就像我脖子上的一个坏结,它似乎已经解决了。

于 2011-09-22T15:30:28.843 回答