Rails / RSpec工厂女孩用无效模型测试会产生奇怪的行为

时间:2015-06-18 18:50:33

标签: ruby-on-rails ruby rspec factory-bot

我正在使用rspec和factory_girl

测试我的rails控制器

我的操作以json格式返回错误消息,如果属性无效,则返回412状态

format.json{render json: user.errors.messages, status: 412}
像这样

当我尝试测试功能时

let(:invalid_attributes){
    FactoryGirl.attributes_for(:user,password: "password")
}
it "returns error if invalid attributes" do
  post :create,{user: invalid_attributes},valid_session
  expect(response).to have_status(412)
end

我收到此错误

 Failure/Error: expect(response).to have_status(412)
       expected #<ActionController::TestResponse:0x00000006f4cc10> to respond to `has_status?`

如果我尝试像这样测试

it "returns error if invalid attributes" do
    user = FactoryGirl.build(:user,invalid_attributes)
    post :create,{user: invalid_attributes},valid_session
    expect(response.body).to eq(user.errors.messages.to_json)
end

我收到此错误

 Failure/Error: expect(response.body).to eq(user.errors.messages.to_json)

       expected: "{}"
            got: "{\"password_confirmation\":[\"doesn't match Password\",\"doesn't match Password\"],\"password\":[\"Password must contain 1 Uppercase alphabet 1 lowercase alphabet 1 digit and minimum 8 charecters\"]}"

有什么问题?提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以像这样测试响应状态:

Turnstile

JSON响应:

}else if (i % 3 & 5 === 0){
console.log('...')