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

Rails / RSpec factory girl testing with invalid model produces strange behaviour

我正在用 rspec 和 factory_girl

测试我的 rails 控制器

我的操作 returns 错误消息,格式为 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\"]}"

有什么问题吗?先谢谢了

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

expect(response.status).to eq(412)

JSON 响应:

expect(response.body).to eq "{\"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\"]}"