rspec mocking "undefined method `stub_model' for #<Class:0x007ff9c339bd80> (NoMethodError)"
I'm using Rails 3.1 and I wanted to add some stubs and mocks to my specs but I get a NoMethodError:
undefined method `stub_model' for #<Class:0x007ff9c339bd80> (NoMethodError)
Here is an excerpt of my GemFile:
gem 'rspec'
gem 'rspec-rails'
I ran bundle install and rails g rspec:install
And here is the code that tries to create a stub_model
0 @flight = stub_model(Flight)
1 Flight.stub! (:all).and_return([@flight])
And here is 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.config开发者_运维知识库ure 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
I'm calling "rspec ./spec" and "bundle exec rspec ./spec" (tried both, no difference)
Everything I'm doing seems to be textbook (in fact, I'm following The Rails 3 Way).
What am I missing?
Chances are that your original code was being run outside of a spec example. This will give the error you describe:
class Foo; end
describe Foo do
@foo = stub_model(Foo)
Foo.stub!(:all).and_return([@foo])
end
but this will work:
class Foo; end
describe Foo do
before do
@foo = stub_model(Foo)
Foo.stub!(:all).and_return([@foo])
end
end
See comment in original question. Like a bad knot in my neck, it seems to have worked itself out.
精彩评论