期望在rspec中多次改变期望

abp*_*kov 7 rspec ruby-on-rails capybara

我试图通过一个动作确保某些数据保持不变:

expect {
  # running migration and user reload here
}.not_to change(user, :avatar_url).from(sample_avatar_url).and change(user, :old_avatar).from(nil)
Run Code Online (Sandbox Code Playgroud)

sample_avatar_url 是在spec文件开头定义的字符串.

基本上,我想检查是否avatar_urlold_avatar保持由发生的事情在触及expect块.

上面代码的输出是:

expect(...).not_to matcher.and matcher不受支持,因为它会产生一些歧义.相反,定义您希望否定RSpec::Matchers.define_negated_matcher和使用的任何匹配器的否定版本expect(...).to matcher.and matcher.

Tho*_*ole 19

这不起作用,因为它不清楚读取是否应该意味着不改变第一个而不是改变第二个,或者不改变第一个但改变第二个.你有几个选择来解决这个问题

由于您正在检查静态值,因此不要使用更改

..run migration and user reload..
expect(user.avatar_url).to eq(sample_avatar_url)
expect(user.old_avatar).to eq nil
Run Code Online (Sandbox Code Playgroud)

或使用define_negated_matcher创建not_change匹配器

RSpec::Matchers.define_negated_matcher :not_change, :change
expect {
  # running migration and user reload here
}.to not_change(user, :avatar_url).from(sample_avatar_url).and not_change(user, :old_avatar).from(nil)
Run Code Online (Sandbox Code Playgroud)

  • 在 rails_helper.rb 中放置 `RSpec::Matchers.define_negated_matcher(:not_change, :change)` 赋予了我的 RSpec 超能力。 (3认同)