【发布时间】:2015-12-11 19:05:45
【问题描述】:
Rspec 在此创建操作上一直失败,即测试运行时事件是 Nil 对象。其他测试通过了我所有的用户和用户令牌身份验证部分。它正在正确加载 Ffaker/Factory-Girl 数据。似乎无法在任何地方找到答案。
events_controller_rspec.rb
describe "POST #create" do
context "when is successfully created" do
before(:each) do
user = FactoryGirl.create(:user)
@event_attributes = FactoryGirl.attributes_for(:event)
api_authorization_header user.auth_token
post :create, { user_id: user.id, event: @event_attributes }, format: :json
end
it "renders the JSON representation for the event record just created" do
event_response = json_response[:event]
expect(event_response[:name]).to eql @event_attributes[:name]
end
it { should respond_with 201 }
end
events_controller.rb
def create
event = current_user.events.build(event_params)
if event.save
render json: event, status: 201, location: [:api, event]
else
render json: { errors: event.errors }, status: 422
end
end
private
def event_params
params.require(:event).permit(:name, :user_id)
end
end
app/concerns/authenticatable.rb
module Authenticable
# Devise methods overwrites
def current_user
@current_user ||= User.find_by(auth_token: request.headers['Authorization'])
end
end
Rspec 结果
Failures:
1) Api::V1::EventsController POST #create when is successfully created renders the JSON representation for the event record just created
Failure/Error: expect(event_response[:name]).to eql @event_attributes[:name]
NoMethodError:
undefined method `[]' for nil:NilClass
# ./spec/controllers/api/v1/events_controller_spec.rb:75:in `block (4 levels) in <top (required)>'
2) Api::V1::EventsController POST #create when is successfully created should respond with 201
Failure/Error: it { should respond_with 201 }
Expected response to be a 201, but was 422
# ./spec/controllers/api/v1/events_controller_spec.rb:78:in `block (4 levels) in <top (required)>'
【问题讨论】:
-
很难调试和重现您的问题。响应有 422 作为状态码,所以问题可能出在对象事件的验证(?)上。如果验证未通过,您可以尝试使用感叹号 (
event.save!) 保存以引发异常。接下来,您可以尝试调试(使用 byebug 或一些 puts)您的规范,例如:将您收到的响应放入标准输出,因此在您的规范中添加puts json_response。 -
这是一个好的开始,帮助我了解了保存到数据库中的一些问题。感谢您的建议!
标签: ruby-on-rails ruby ruby-on-rails-4 rspec