ruby-on-rails - RSpec,期望随着多个值的变化而变化

标签 ruby-on-rails rspec

Possible Duplicate:
Is it possible for RSpec to expect change in two tables?

it "should create a new Recipe" do
  expect { click_button submit }.to change(Recipe, :count).by(1)
end

这使我能够检查“食谱”模型是否多了一个条目,但我还想检查“成分”模型是否多了一个条目。由于表单已经提交,expect block 只能执行一次。

我知道我可以再制作一个“it” block ,但我觉得必须有一种更干燥的方法。

最佳答案

我建议通过重新定义测试主题来干燥它(并使用 stabby lambdas 来娱乐):

describe "recipe creation" do
  subject { -> { click_button submit } }
  it { should change(Recipe, :count).by(1) }
  it { should change(Ingredient, :count).by(1) }
end

更新:虽然它可能看起来不太干燥,但这些天我可能仍然会继续使用 expect 语法,因为它是 recommended我通常会放弃应该,但也许会为了规范的可读性做一些小的改变:

describe "recipe creation" do
  let(:creating_a_recipe) { -> { click_button submit } }

  it "changes the Recipe count" do
    expect(creating_a_recipe).to change(Recipe, :count).by(1)
  end

  it "changes the Ingredient count" do
    expect(creating_a_recipe).to change(Ingredient, :count).by(1)
  end
end

注意:您可能会在 RSpec documentation for the change matcher 中看到expect 使用大括号。这当然是正确的,但标准括号在此示例中起作用的原因是更改可变状态的代码(包含在 creating_a_recipe 中)位于 lambda 中,当传递到 时会调用该 lambda >expect 作为参数。

无论如何,在这种情况下,expect(creating_a_recipe)expect {create_a_recipe } 都可以成功使用,具体使用哪一个就看个人喜好了。

关于ruby-on-rails - RSpec,期望随着多个值的变化而变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13966022/

相关文章:

ruby-on-rails - rspec Controller 测试,获取多个参数

unit-testing - RSpec 与 Cucumber(RSpec 故事)

ruby-on-rails - any_instance should_receive 无法正常工作

ruby-on-rails - 使用 Rspec 测试无效电子邮件

ruby-on-rails - Vue 在 Capybara 测试中没有渲染

ruby-on-rails - Rail 4 中的批量分配 protected 属性

ruby-on-rails - rails : What's the difference between capture and content_for?

ruby-on-rails - 如何使用 Rspec 正确显示双引号的 ""

ruby-on-rails - 如何在现有的 Rails 应用程序中安装 Slate?

mysql - 在单个查询中捕获一列具有最高值的记录?