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

后端 未结 8 1549
借酒劲吻你
借酒劲吻你 2020-12-09 07:15

RSpec expect change:

it \"should increment the count\" do
  expect{Foo.bar}.to change{Counter.count}.by 1
end

Is there a way to expect chan

相关标签:
8条回答
  • 2020-12-09 08:12

    The best way I've found is to do it "manually":

    counters_before         = Counter.count
    another_counters_before = AnotherCounter.count
    Foo.bar
    expect(Counter.count).to eq (counters_before + 1)
    expect(AnotherCounter.count).to eq (another_counters_before + 1)
    

    Not the most elegant solution but it works

    0 讨论(0)
  • 2020-12-09 08:19

    I'm ignoring the best practices for two reasons:

    1. A set of my tests are regression tests, I want them to run fast, and they break rarely. The advantage of having clarity about exactly what is breaking isn't huge, and the slowdown of refactoring my code so that it runs the same event multiple times is material to me.
    2. I'm a bit lazy sometimes, and it's easier to not do that refactor

    The way I'm doing this (when I need to do so) is to rely on the fact that my database starts empty, so I could then write:

    foo.bar
    expect(Counter.count).to eq(1)
    expect(Anothercounter.count).to eq(1)
    

    In some cases my database isn't empty, but I either know the before count, or I can explicitly test for the before count:

    counter_before = Counter.count
    another_counter_before = Anothercounter.count
    
    foo.bar
    
    expect(Counter.count - counter_before).to eq(1)
    expect(Anothercounter.count - another_counter_before).to eq(1)
    

    Finally, if you have a lot of objects to check (I sometimes do) you can do this as:

    before_counts = {}
    [Counter, Anothercounter].each do |classname|
      before_counts[classname.name] = classname.count
    end
    
    foo.bar
    
    [Counter, Anothercounter].each do |classname|
      expect(classname.count - before_counts[classname.name]).to be > 0
    end
    

    If you have similar needs to me this will work, my only advice would be to do this with your eyes open - the other solutions proposed are more elegant but just have a couple of downsides in certain circumstances.

    0 讨论(0)
提交回复
热议问题