[英]Rspec: Access a controller concern's methods in request specs
I have a controller concern defined as follows:我有一个 controller 问题,定义如下:
module Auth
extend ActiveSupport::Concern
private
def sign_in(user)
session[:customer_id] = user.id
self.current_user = user
end
def signed_in?
!current_user.nil?
end
...
# other methods
end
And this module is included in the ApplicationController
:这个模块包含在
ApplicationController
中:
class ApplicationController < ActionController::Base
include Auth
helper_method :signed_in?, :current_user, :current_user?
before_action :authorize
end
The questions I have:我的问题:
extend ActiveSupport::Concern
in a concern?extend ActiveSupport::Concern
吗? If so wy and when not? I tried to add the following in spec/support/utilities.rb
:我尝试在
spec/support/utilities.rb
中添加以下内容:
include ApplicationHelper
include Auth
as well as required all the files from spec/support
directory in rails_helper.rb
and included the above modules:以及所需的所有来自
rails_helper.rb
中spec/support
目录的文件,并包含上述模块:
# Require all the files in support directory
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
...
# include ApplicationHelper
config.include ApplicationHelper, type: :feature
config.include Auth, type: :request
...
end
Now, when running a requests/customers_spec.rb
:现在,在运行
requests/customers_spec.rb
时:
require 'rails_helper'
RSpec.describe "/customers", type: :request do
describe "GET /index" do
it "renders a successful response" do
customer = create(:customer)
sign_in(customer)
get customers_url
expect(response).to be_successful
end
end
...
it fails with:它失败了:
Failures:
1) /customers GET /index renders a successful response
Failure/Error: session[:customer_id] = user.id
NoMethodError:
undefined method `session' for nil:NilClass
# ./app/controllers/concerns/auth.rb:7:in `sign_in'
# ./spec/requests/customers_spec.rb:10:in `block (3 levels) in <top (required)>'
What am I missing?我错过了什么? I'm using Rails
6.0.3
, rspec-rails 4.0.1
.我正在使用 Rails
6.0.3
, rspec-rails 4.0.1
。
The solution I came to was to add the following method to the spec/support/login_macros.rb
:我来到的解决方案是将以下方法添加到
spec/support/login_macros.rb
:
module LoginMacros
def sign_in_with_browser(user)
visit login_path
fill_in 'E-mail', with: user.email
fill_in 'Password', with: user.password
click_button 'Login'
end
def sign_out_with_browser
click_link 'Logout'
end
# to enable user authentication in request specs
def login_without_browser(user)
post login_url, params: { email: user.email, password: 'secret' }
end
end
Then test a protected end-point in the above request spec as follows:然后在上述请求规范中测试一个受保护的端点,如下所示:
describe "GET /index" do
it "renders a successful response" do
customer = create(:customer)
login_without_browser(customer)
get customers_url
expect(response).to be_successful
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.