Ruby on rails 为导致RSpec测试失败的api设计登录
我正在使用Rails和Desive构建一个API。我的会话控制器继承自以下基本控制器Ruby on rails 为导致RSpec测试失败的api设计登录,ruby-on-rails,rspec,devise,Ruby On Rails,Rspec,Devise,我正在使用Rails和Desive构建一个API。我的会话控制器继承自以下基本控制器 api/base_controller.rb module Api class BaseController < ApplicationController skip_before_filter :verify_authenticity_token before_filter :authenticate_user_from_token! respond_to :json
api/base_controller.rb
module Api
class BaseController < ApplicationController
skip_before_filter :verify_authenticity_token
before_filter :authenticate_user_from_token!
respond_to :json
private
def authenticate_user_from_token!
user_token = params[:auth_token].presence
user = user_token && User.find_by_authentication_token(user_token)
if user
sign_in user, store: false
else
render :json => {:success => false, :message => "Error with your credentials", :status => 401}
end
end
end
end
这在通过curl测试api时非常有效。但是,我无法通过销毁操作的Rspec测试。从Rspec,用户调用中的sign_失败,因此响应是重定向。我尝试在方法中存根sign_没有任何成功
Rspec测试:
describe "DELETE destroy" do
before(:each) do
@user1 = User.create!(:email => 'example@gmail.com', :password => 'helloworld', :password_confirmation => 'helloworld')
end
it "should render success json" do
delete :destroy, :auth_token => @user1.authentication_token
json = JSON.parse(response.body)
json.should include('success' => true, 'status' => 200)
end
###this fails because the response is a redirect to the sign_in page
end
如何模拟从基本控制器中调用的sign_-in方法?添加一个
spec/support/designe.rb
文件,其中包含以下内容:
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
另外,检查test.log是否实际使用json格式。我遇到了一个类似的问题,发现我必须在spec调用参数中强制使用
格式:json
Andreamazz指给我看test.log,它显示我创建的用户已被确认(我正在使用designe confirmable)。我使用user.confirm!在过去,一切都在流逝
describe "DELETE destroy" do
before(:each) do
@user1 = User.create!(:email => 'example@gmail.com', :password => 'helloworld', :password_confirmation => 'helloworld')
@user1.confirm!
end
it "should render success json" do
delete :destroy, :auth_token => @user1.authentication_token
json = JSON.parse(response.body)
json.should include('success' => true, 'status' => 200)
end
end
谢谢 我已将其包含在spec_helper.rb文件中。我可以在Rspec测试中使用sign_in(@user)很好,但是来自基本控制器中的sign_in调用仍然会导致重定向到sign_in路径。你能在test.log中检查它是否实际使用json格式吗?我遇到了一个类似的问题,并且发现我必须在我的规范调用中强制使用
格式:json
。感谢您向我指出测试日志!它正在请求HTML,但这似乎不是问题所在。我意识到我正在使用Deviate confirmable,并且正在创建一个未经确认的用户,导致登录时重定向。我设置@user1。跳过确认!所有测试都通过了!这修复了我从rspec测试中得到的错误。。。NoMethodError:nil:NilClass的未定义方法“user”即时Google没有发现任何结果,希望这条评论能有所帮助。
describe "DELETE destroy" do
before(:each) do
@user1 = User.create!(:email => 'example@gmail.com', :password => 'helloworld', :password_confirmation => 'helloworld')
@user1.confirm!
end
it "should render success json" do
delete :destroy, :auth_token => @user1.authentication_token
json = JSON.parse(response.body)
json.should include('success' => true, 'status' => 200)
end
end