我使用Rails 5和minitest。我想测试一个需要登录的控制器方法,由控制器中的过滤器验证
before_filter :require_current_user
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
def require_current_user
redirect_to(:root, :notice => "you must be logged in") unless current_user
end
为了模拟会话变量,我在测试中添加了这个
def setup
@logged_in_user = users(:one)
session[:user_id] = @logged_in_user.id
end
test "do create" do
person = people(:one)
rating
post rate_url, params: {person_id: person.id, rating: rating}
# Verify we got the proper response
assert_response :success
end
但是当我运行上述测试时,会导致错误
NoMethodError: undefined method `session' for nil:NilClass
test/controllers/rates_controller_test.rb:10:in `setup'
如何在minitest中模拟会话变量?
编辑:根据给出的回复,这是我的session_create方法
def create
puts "env: #{env["omniauth.auth"]}"
user = User.from_omniauth(env["omniauth.auth"])
first_login = user.last_login.nil?
# Record the fact that this is their first login in the session
session[:first_login] = first_login
# Record the last login of the user
user.last_login = Time.now
user.save
session[:user_id] = user.id
last_page_visited = session[:last_page_visited]
session.delete(:last_page_visited)
url = last_page_visited.present? ? last_page_visited : url_for(:controller => 'votes', :action => 'index')
redirect_to url
end
答案 0 :(得分:0)
我认为这对你有用。
public getJSON(): Observable<any> {
return this.http.get("./export.json")
.map(res => {var data = res.json(); return data});
}
看看here
您还可以发布每个测试的登录页面并设置会话
controller.session[:user_id] = users(:one).id
结帐this
答案 1 :(得分:0)
在Rails 4.2中, ActionController :: TestCase 可以工作:
@controller.session[:user_id] = users(:one).id
也许Rails 5也可以使用。