使用rspec进行模型测试

Aru*_*rma 5 rspec

我有一段我要测试的代码:

class User < ActiveRecord::Base

 has_many :servers, :dependent=> :destroy

end
Run Code Online (Sandbox Code Playgroud)

请举例说明测试关联代码的RSpec代码.

ka8*_*725 8

对我来说,这种变体效果很好:

describe User do
  it { should have_many(:servers).dependent(:destroy) }
end
Run Code Online (Sandbox Code Playgroud)


小智 0

在 RSpec 中测试关联的一种方法是使用shoulda。Shoulda 是一个帮助程序的集合,可以使常见的重复测试快速编写,同时易于理解。要测试您的模型,请确保已安装并需要 shoulda gem。然后您可以使用如下内容来测试您的关联:

describe User do
  it {should have_many :servers, :dependent => :destroy}
end
Run Code Online (Sandbox Code Playgroud)