让我先声明一下,我是 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,而是抛出了一个错误。我将如何正确捕获该错误并通过测试?
谢谢!
最佳答案
假设您的模型如下所示:
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
关于ruby-on-rails - Rspec Postgres 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098702/