我正在为api会话控制器create动作编写功能测试。这是我正在运行的代码:
这是我的api session_controller.rb
class Api::V2::Users::SessionsController < Api::V2::BaseController
prepend_before_action :allow_params_authentication!, only: :create
skip_before_action :authenticate_user!, only: :create
def create
resource = warden.authenticate!(scope: :user)
sign_in(:user, resource)
yield resource if block_given?
render json: {access_token: current_token, user: resource}
end
def destroy
signed_out = (Devise.sign_out_all_scopes ? sign_out :
sign_out(resource_name))
yield if block_given?
head :no_content
end
private
def current_token
request.env['warden-jwt_auth.token']
end
end
这是我的sessions_controller_test.rb
require 'test_helper'
require 'devise/jwt/test_helpers'
//controller_test
class SessionsControllerTest < ActionDispatch::IntegrationTest
token = Knock::AuthToken.new(payload: { sub: user.id }).token
token = { 'Authorization': "Bearer #{token}" }
URL = '/v2/users?me=true'
AUTH_URL = '/user_token'
describe 'GET /users?me=true' do
it 'should return the user info' do
user = create(:user)
get URL, headers: authenticated_header(user)
puts response.body
end
end
describe "aunauthorised user" do
it 'should return unauth for retrieve current user info before
login' do
get URL
expect(response).to have_http_status(:unauthorized)
end
end
end
我需要运行测试,就像成功创建用户时显示成功消息一样。我希望它在成功创建用户时会生成令牌。
答案 0 :(得分:0)
第一件事:通常最好的做法是在每个it
块中仅测试一件事。这样,可以更轻松地验证您是否已涵盖特定情况,并执行拆卸和设置测试。
我相信您可以从这样的事情中受益:
let(:action) { post url, params: params }
let(:url) { "/users" } # change this to correct path matching your router
let(:params) {
{
username: "username1",
password: "secret-password",
},
}
it "generates user token" do
expect { action }.to change { user.tokens.count }.by(1)
end
it "returns the access token" do
action
expect(response.body).to include(user.tokens.last)
end
it "returns the user information" do
action
expect(response.body).to include user.to_json
end
我希望这会有所帮助。
最好