【问题标题】:Rails / RSpec factory girl testing with invalid model produces strange behaviourRails / RSpec 工厂女孩使用无效模型进行测试会产生奇怪的行为
【发布时间】:2015-06-18 18:50:32
【问题描述】:

我正在使用 rspec 和 factory_girl 测试我的 rails 控制器

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

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\"]}"

有什么问题?提前谢谢

【问题讨论】:

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


    【解决方案1】:

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

    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\"]}"
    

    【讨论】:

    • 因为user 是您的工厂。为什么会有错误?
    • 但我将 invalid_attributes 传递给它
    • 因为你只调用了build就可以了。在运行验证之前不会填充错误,并且在您尝试调用 .save.valid? 或使用 create 而不是 build 之前不会运行验证。
    • 感谢您提供这些有用的信息,但是为什么它在错误消息中返回一个数组?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2012-07-16
    • 2012-01-03
    相关资源
    最近更新 更多