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 に答える