【问题标题】:Rspec Postgres ErrorRspec Postgres 错误
【发布时间】:2010-06-23 03:15:10
【问题描述】:

首先让我说我是 TDD 和 Ruby on Rails 的新手。

我正在使用 Rspec 对我的数据层执行单元测试,并确保我的数据库拒绝无效输入。

我的 rspec 代码如下所示:

it "should fail at saving without name" do
  @my_data.attributes = valid_my_data_attributes.except(:name)
  @my_data.save_with_validation( false ).should be_false
end

我的数据库 (Postgres) 正确拒绝数据,但不是返回 false,而是抛出错误。我怎样才能正确捕捉到该错误并通过测试?

谢谢!

【问题讨论】:

    标签: ruby-on-rails postgresql tdd rspec


    【解决方案1】:

    假设您的模型如下所示:

    class Customer
      validates_presence_of :name, :other_attribute
    end
    

    在您的规范中,您可以检查模型在特定属性上是否存在错误

    it "should require name" do
      create_customer(:name => nil).should have(1).errors_on(:name)
    end
    
    it "should create a valid customer" do
      create_customer.should be_valid
    end
    
    # factory method
    def create_customer(attributes = {})
       Customer.create({:name => 'foo', :other_attribute => 'foo'}.merge(attributes))
    end
    

    【讨论】:

    • 我实际上最终得到了两个错误,但这是因为我对 :name 有两个约束,一个用于 NOT NULL,一个用于 LENGTH > 0,所以如果我使用 :name => 进行测试"",我得到一个长度错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多