Почему методы RSpec, "get", "post", "put", "delete" работают в спецификации контроллера в драгоценном камне (или вне Rails)?
Я не новичок в Rails или Rspec, но я новичок в создании драгоценных камней. Когда я тестирую свои контроллеры, методы REST "get", "post", "put", "delete" дают мне ошибку метода undefined.
Ниже вы найдете код, но если вы предпочитаете его видеть в пасте, нажмите здесь.
Спасибо!
Здесь мой spec_helper:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rubygems'
require 'active_support' unless defined? ActiveSupport # Need this so that mattr_accessor will work in Subscriber module
require 'active_record/acts/subscribable'
require 'active_record/acts/subscriber'
require 'action_view'
require 'action_controller' # Since we'll be testing subscriptions controller
#require 'action_controller/test_process'
require 'spec'
require 'spec/autorun'
# Need active_support to user mattr_accessor in Subscriber module, and to set the following inflection
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'dorkus', 'dorkuses'
end
require 'active_record' # Since we'll be testing a User model which will be available in the app
# Tell active record to load the subscribable files
ActiveRecord::Base.send(:include, ActiveRecord::Acts::Subscribable)
ActiveRecord::Base.send(:include, ActiveRecord::Acts::Subscriber)
require 'app/models/user' # The user model we expect in the application
require 'app/models/person'
require 'app/models/subscription'
require 'app/models/dorkus'
require 'app/controllers/subscriptions_controller' # The controller we're testing
#... more but I think irrelevant
Мои подписки_спец:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe SubscriptionsController, "on GET index" do
load_schema
describe ", when only subscribable params are passed" do
it "should list all the subscriptions of the subscribable object"
end
describe ", when only subscriber params are passed" do
it "should list all the subscriptions of the subscriber" do
u = User.create
d1 = Dorkus.create
d2 = Dorkus.create
d1.subscribe! u
d2.subscribe! u
get :index, {:subscriber_type => "User", :subscriber_id => u.id}
assigns[:subscriptions].should == u.subscriptions
end
end
end
Мой контроллер подписок:
class SubscriptionsController < ActionController::Base
def index
end
end
Ошибка:
NoMethodError in 'SubscriptionsController on GET index , when only subscriber params are passed should list all the subscriptions of the subscriber'
undefined method `get' for #
/home/ramon/rails/acts_as_subscribable/spec/controllers/subscriptions_controller_spec.rb:21:
Ответы
Ответ 1
Поскольку эти методы не относятся к Rspec, а относятся к Rails.
Когда вы описываете контроллер, он наследует от Spec:: Rails:: Example:: ControllerExampleGroup, который наследует FunctionalExampleGroup, который наследует рельсы ActionController:: TestCase.
Если вы посмотрите Документацию ActionController:: TestCase, вы обнаружите, что там, где определены методы get/post/put/delete.
Итак, если вы хотите получить доступ к этим методам вне Rails, вам нужно переопределить их.
Ответ 2
Добавление: type = > контроллер для описания следующим образом работал у меня
describe TestController, :type => :controller do
# ur stuff
end
Ответ 3
Теперь связь с принятым ответом выше. Здесь обновленная ссылка (для 2.3.8)
http://api.rubyonrails.org/v2.3.8/classes/ActionController/TestCase.html
Ответ 4
У меня была эта проблема с драгоценным камнем, который я делаю для системы Rails 2.3.8. Затем я понял, что использую версию Rspec-Rails выше 2.0, когда я должен использовать последнюю версию Rspec-Rails-1.3 (версия 1.3.4).
Я удалил все связанные с RSpec-Rails v2 gems (rspec-core, rspec-ожидания, rspec-mocks и т.д.), настроил мой Gemfile с помощью v1.3.4 и запустил 'bundle install'.
Я использую фиктивное приложение Rails 2.3.8 в spec/dummy, настроенное на использование Bundler, и с Gemfile, настроенным с теми же характеристиками gem, что и мои Gem Gemfile (который захватывает драгоценные камни из файла gemspec).
Я запускал 'script/generate rspec' для создания файлов/папок RSpec для Rails, на которые я ссылался, чтобы сделать соответствующие конфигурации в моих файлах Rakefile и spec_helper.