问题与apipie gem和rspec在rails 4中

时间:2015-11-07 16:47:48

标签: ruby-on-rails api rspec

我正在编写代码以让我的Rspec测试通过我的api。我使用apipie gem来生成文档,似乎我的测试失败了,因为你期待一个数字并且很有趣,因为这正是我想要测试的。 当:bpm参数不是数字时页面失败。有什么方法可以解决这个问题吗?

context "when is not created" do
  before(:each) do
    user = FactoryGirl.create :user
    @invalid_lesson_attributes = { title: "California Dreamin",
                                   bpm: "Hello"

    }
    request.headers['Authorization'] =  user.auth_token
    post :create, { user_id: user.id, lesson: @invalid_lesson_attributes }
  end


  it "renders an errors json" do
    lesson_response = json_response
    expect(lesson_response).to have_key(:errors)
  end
  it "renders the json errors on why the user could not be created" do
    lesson_response = json_response
    expect(lesson_response[:errors][:bpm]).to include "is not a number"
  end

  it { should respond_with 422 }

  end
end

更新规范:

context "when is not updated" do
  before(:each) do
    patch :update, { user_id: @user.id, id: @lesson.id,
                     lesson: { bpm: "ten" }, format: :json }
  end

  it "renders an errors json" do
    lesson_response = json_response
    expect(lesson_response).to have_key(:errors)
  end

  it "renders the json errors on why the user could not be updated" do
    lesson_response = json_response
    expect(lesson_response[:errors][:bpm]).to include "is not a number"
  end

  it { should respond_with 422 }
end

在我的users_controller中:

api :POST, '/teachers/:user_id/lessons/', "Create lesson"
param :lesson, Hash, desc: 'Lesson information', :required => true do
  param :title, String, desc: 'Title of the lesson', :required => true
  param :bpm, :number, desc: 'tempo of the lesson (beats per second)', :required => true

end
error :code => 422, :desc => "Unprocessable Entity"

运行我的rspec测试时的错误:

Apipie::ParamInvalid: Invalid parameter 'bpm' value "Hello": Must be a number.

1 个答案:

答案 0 :(得分:0)

将格式json添加到帖子请求

post :create, { user_id: user.id, lesson: @invalid_lesson_attributes, format: :json }

这对我有用。