我目前正在使用Rails首次实现API,并且在使用RSpec进行请求测试时遇到了一些意外错误。截至目前,我已经验证我的模型和控制器已正确设置,因为我可以POST
使用curl
进行数据库curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/v1/users -d "{\"user\":{\"email\":\"user1@example.com\",\"password\":\"somepassword\",\"password_confirmation\":\"somepassword\"}}"
,如下所示:
registrations_controller.rb
不幸的是,当我从我的RSpec测试中发出相同的请求时,服务器返回时发出错误,指出该电子邮件已被删除。唯一的问题是这个错误没有意义,因为我使用Faker创建电子邮件和DatabaseCleaner来清理测试数据库。这是我的设置,以及我的测试日志的副本。
class Api::V1::Users::RegistrationsController < Devise::RegistrationsController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format == 'application/json' }
respond_to :json
def create
build_resource (user_params)
if resource.save
sign_in resource
render :status => 200,
:json => { :success => true,
:info => "Registered",
:data => { :user => resource,
:auth_token => resource.authentication_token } }
else
render :status => :unprocessable_entity,
:json => { :success => false,
:info => resource.errors,
:data => {} }
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
:
spec/factories/user.rb
FactoryGirl.define do
password = Faker::Internet.password(10)
factory :user do |user|
user.email { Faker::Internet.email }
user.password { password }
user.password_confirmation { password }
end
end
:
spec/api/v1/user/user_spec.rb
require 'spec_helper'
describe 'POST /v1/users' do
it "allows new users to register with an email address and password" do
user = FactoryGirl.create(:user)
post '/v1/users', {
user: {
email: user.email,
password: user.password,
password_confirmation: user.password_confirmation
}
}.to_json, { 'Content-Type' => 'application/json',
'Accept' => 'application/json' }
puts response.body
end
end
:
{"success":false,"info":{"email":["has already been taken"]},"data":{}}
服务器响应如下:{{1}}。我已经尝试了一切来解决这个问题,但不幸的是失败了。任何人都可以在我的实现中发现错误吗?我很感激帮助。
答案 0 :(得分:2)
您已使用
在数据库中创建用户user = FactoryGirl.create(:user) ## Creates a user record in database
然后尝试注册同一个用户(通过Api::V1::Users::RegistrationsController#create
注册创建相同的用户),这就是您收到错误的原因:
"email":["has already been taken"] ## due to uniqueness constraint on email
您需要做的只是使用FactoryGirl构建一个User类实例:
user = FactoryGirl.build(:user) ## Use "build" (which builds an instance of User) and NOT "create" method
并让注册方法,即Api::V1::Users::RegistrationsController#create
负责用户创建。