rspec用于测试更改计数的笨拙语法

时间:2016-06-29 22:22:00

标签: ruby-on-rails ruby rspec

我的rspec测试看起来像这样:

describe 'on DELETE to :destroy' do
  before do
    expect { delete :destroy, id: 6 }.to change(ModelName, :count)
  end

  it { is_expected.to respond_with :success }
  it { is_expected.to render_template :destroy }
end

我发现在before块内部对变更计数进行测试很尴尬,而且我不需要运行它两次。我希望找到类似这样的语法:

describe 'on DELETE to :destroy' do
  before do
    delete :destroy, id: 6
  end

  it { is_expected.to respond_with :success }
  it { is_expected.to render_template :destroy }
  it { is_expected.to change(ModelName, :count) }
end

然而,第三次测试给出了以下错误:

expected #count to have changed, but was not given a block

1 个答案:

答案 0 :(得分:0)

正如错误消息所示,您需要传递一个块,例如:

it { is_expected.to change { ModelName.count } }