Ne peut pas stub choses avec Rspec
J'ai un Rails 4 application, et voici ma lib/foobar:
jan@rmbp ~/D/r/v/l/foobar> tree
.
├── foo_bar.rb
└── foobar_spec.rb
0 directories, 2 files
Et les fichiers:
foobar_spec.rb
require "spec_helper"
describe "FooBar" do
subject { FooBar.new }
its(:foo) { should == "foo"}
#stubbed version of test crashes
#FooBar.stub(:foo).and_return("bar")
#subject { FooBar.new }
#its(:foo) { should == "bar"}
end
foo_bar.rb
class FooBar
def foo
"foo"
end
end
spec_helper.rb.rb:
# This file is copied to spec/when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
# commented for zeus two runs bug
require 'rspec/autorun'
require 'capybara/rspec'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
config.include Features::SessionHelpers, type: :feature
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
end
La spec passe bien. Mais quand je décommentez cette ligne:
# FooBar.stub(:foo).and_return("bar")
Il échoue avec:
/Users/jan/.rvm/gems/ruby-2.0.0-p247/gems/rspec-mocks-2.14.3/lib/rspec/mocks.rb:26:in `proxy_for': undefined method `proxy_for' for nil:NilClass (NoMethodError)
Quel est le problème?
EDIT:
Aussi, je ne peux pas semblent être en mesure d'utiliser webmock
.
stub_request(:post, "https://accounts.google.com/o/oauth2/token")
.with(:body => { "client_id" => CLIENT_ID,
"client_secret" => CLIENT_SECRET,
"refresh_token" => refresh_token, }
).to_return(:status => 200,
:body => File.read("#{$fixtures}/refresh_token.json"))
Retourne:
/Utilisateurs/jan/Documents/ruby/vince.re/lib/youtube/you_tube_test.rb:9:
block in <top (required)>': undefined method
stub_request " pour
< Catégorie :0x007f8159bbe7c0> (NoMethodError)
SOLUTION:
Grâce à @gotva pour me dire à propos de talons obligation de résider dans it
blocs. Voici ma nouvelle, fixe webmock test, et il fonctionne très bien:
context "when token is nil it" do
it "called refresh method" do
YouTube.any_instance.should_receive(:refresh_auth_token).with(data["refresh"])
YouTube.new(data["uid"], nil, data["refresh"])
end
it "refreshed the authentation token" do
stub_request(:post, "https://accounts.google.com/o/oauth2/token")
.with(:body => { "client_id" => CLIENT_ID,
"client_secret" => CLIENT_SECRET,
"grant_type"=>"refresh_token",
"refresh_token" => data["refresh"], }
).to_return(:status => 200,
:body => File.read("#{$fixtures}/refresh_token.json"))
yt = YouTube.new(data["uid"], nil, data["refresh"])
yt.token.should == data["access_token"]
end
end
OriginalL'auteur if __name__ is None | 2013-09-08
Vous devez vous connecter pour publier un commentaire.
Il me semble que l'utilisation de ce talon
vous essayez de stub une méthode inexistante.
Méthode
foo
est de la méthode d'instance, mais vous avez de la classe de stub méthode.Si vous souhaitez stub méthode d'instance FooBar#foo utilisation
any_instance
Mise à jour à partir des commentaires
Appliquer
stub
dansit
oubefore
blocs.nouvelle variante:
ou
le lieu de stub pour me confondre. 1. Stub doit être placé dans
it
bloc ou en avant de bloc. 2. il doit être placé avant la réelle méthode sera appelée. faire ces changements et de dire si l'exception est toujours làsur stub_request. A votre Gemfile gem
webmock
?1. Je sais. 2. Je sais. Oui, c'est fait. 3. Oui, j'ai
webmock
dans le gemfile et installé.Oups, 1. il fixe. On dirait que je ne connaissais pas 🙂
OriginalL'auteur