在 RSpec 中测试模型属性时避免重复

Avoid duplication while testing model attributes in RSpec

我有几个模型,在这个模型中我有一些我不想留空的属性。

我想使用 RSpec 和 Factory Girl 根据这些限制对我的模型进行大量测试。

但是我最终得到了代码重复:

user_spec:

it 'is invalid if blank' do
  expect {
   FactoryGirl.create(:user, nickname => '')
  }.to raise_error(ActiveRecord::RecordInvalid)
end

message_spec:

it 'is invalid if blank' do
  expect {
   FactoryGirl.create(:message, :re => '')
  }.to raise_error(ActiveRecord::RecordInvalid)
end

我如何分解它?

RSpec 提供了几种方法,例如 Shared Examples.

1.在 [RAILS_APP_ROOT]/support/

中创建一个文件

根据您的示例,您可以将此文件命名为 not_blank_attribute.rb。然后,您只需将复制的代码移入并调整它以使其可配置:

RSpec.shared_examples 'a mandatory attribute' do |model, attribute|
  it 'should not be empty' do
    expect {
      FactoryGirl.create(model, attribute => '')
    }.to raise_error(ActiveRecord::RecordInvalid)
  end
end

2。在您的规范中使用 it_behaves_like 函数

此函数将调用共享示例。

RSpec.describe User, '#nickname' do
  it_behaves_like 'a mandatory attribute', :User, :nickname
end

最后输出:

User#nickname
  behaves like a mandatory attribute
      should not be empty