我正在尝试在Rails中编写Rspec测试,使用Devise帮助方法进行登录和注销 . sign_in方法无效 . 但是,在对应用程序进行一系列更改之前,它已经提前工作了 .
我尝试过的事情:
-
我在Rspec.configure中包含测试助手 .
-
使用Warden的login_as
-
清除Rails缓存 .
-
摆脱Capybara,看看是否导致了这个问题
-
我没有在我的控制器规范中明确设置会话(例如没有valid_session)
到目前为止,没有骰子 . 使用已登录用户测试控制器需要做些什么?
错误信息:
OrderItemsController GET #index renders the :index view
Failure/Error: sign_in :admin
NoMethodError:
undefined method `sign_in' for # <RSpec::ExampleGroups::OrderItemsController_2::GETIndex:0x00000102c002d0>
# ./spec/controllers/order_items_controller_spec.rb:6:in `block (2 levels) in <top (required)>'
控制器规格
require 'spec_helper'
describe OrderItemsController do
before (:each) do
admin = create(:admin)
sign_in :admin
end
describe "GET #index" do
it "renders the :index view" do
get :index
expect( response ).to render_template :index
end
end
end
spec_helper.rb
require 'rspec/rails'
require 'capybara/rspec'
RSpec.configure do |config|
config.include ApplicationHelper
config.include ControllersHelper
config.include UsersHelper
config.include Devise::TestHelpers, type: :controller
config.include FactoryGirl::Syntax::Methods
end
的Gemfile
group :development, :test do
gem 'rspec-rails', '~> 3.0.0.beta'
gem 'capybara'
gem 'factory_girl_rails'
gem 'faker'
gem 'dotenv-rails'
gem 'guard'
gem 'guard-annotate'
gem 'guard-rspec', require: false
gem 'guard-livereload', require: false
gem 'foreman'
end
工厂/ user.rb
FactoryGirl.define do
factory :user do
first { Faker::Name.first_name }
last { Faker::Name.last_name }
email { Faker::Internet.email }
admin false
password "secrets1"
password_confirmation "secrets1"
confirmed_at Date.today
factory :admin do
admin true
end
end
end
提前致谢 .
5 回答
您最近是否像我一样升级到RSpec 3?这是the RSpec 3 documentation:
添加该配置代码段后,我不再需要指定规范类型(例如
type: :controller
) .我想出了一个解决方案 . 我明确地将控制器的描述块定义为控制器类型 .
我仍然不明白为什么这段代码早先工作但现在需要这个(看似多余的)显式声明 . 无论如何,我很感激学习这里发生的事情 . 谢谢!
我可以为你提供一个例子(适用于我 - rspec / capybara / simplecov等...)
spec/spec_helper.rb
spec/integration/user_flow_spec.rb
我希望它会好的:)我认为你的问题是缺少Warden测试助手......
您可以在文件spec / spec_helper.rb中使用Devise助手:
对于Rails 5和Rspec 3,您需要将其添加到spec_helper.rb中