khelll
khelll

Reputation: 23990

calling rspec directly on a model results on errors in stub! method

When running:

rake spec:models

everything works well, but when I do

rspec spec/models/spot_spec.rb

that has Spot.stub! :test1 , I get:

undefined method `stub!' for Spot:Class

The error happens only when I include that stub! line.

Any ideas how to avoid it? I want to run the specs for a specific model only.

Update:

Using Ruby 1.9.2 and RSpec 2.4.0, here is the spot_spec.rb code:

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

And the 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

Upvotes: 4

Views: 1954

Answers (2)

khelll
khelll

Reputation: 23990

Turned out to be an issue in before(:all) call:

That's correct. Mocks are implicitly verified and cleared out after(:each) so they won't work in before(:all).

Changing it to before(:each) solved it.

Thanks everyone.

Upvotes: 14

Steve Wilhelm
Steve Wilhelm

Reputation: 6260

Have spot_spec.rb include spec_helper.rb and then make sure spec_helper.rb includes spot_spec.rb.

If you are running ruby 1.9+, you can use require_relative to include spot_spec.rb in spec_helper.rb

Update:

in spec_helper.rb add:

require_relative '../app/models/spot'

Upvotes: 1

Related Questions