RSpec:未定义的方法'assert#u difference';对于(命名者)

RSpec:未定义的方法'assert#u difference';对于(命名者),rspec,rspec2,rspec-rails,Rspec,Rspec2,Rspec Rails,我在谷歌上搜索了这个错误,但没有找到可以修复的。 请帮帮我。谢谢:)确保在spec/spec\u helper.rb中包含AssertDifference: context 'with event_type is available create event' do let(:event_type) { EventType.where( name: 'visit_site').first } assert_difference 'Event.count' do Event.fir

我在谷歌上搜索了这个错误,但没有找到可以修复的。
请帮帮我。谢谢:)

确保在spec/spec\u helper.rb中包含AssertDifference:

context 'with event_type is available create event' do
  let(:event_type) { EventType.where( name: 'visit_site').first }
  assert_difference 'Event.count' do
    Event.fire_event(event_type, @sponge,{})
  end
end
并将断言放入
it
块中:

RSpec.configure do |config|
  ...   
  config.include AssertDifference
end

我最好用英文重写一下

这在RSpec3.x中肯定是可行的,但在旧版本中也可能如此

it 'event count should change' do
  assert_difference 'Event.count' do
    ...
  end
end

如果您使用的是RSPEC,那么“更改”肯定是一个不错的选择。这里有两个示例,一个是否定的,一个是肯定的,这样您就可以了解语法:

context 'with event_type is available create event' do
  let(:event_type) { EventType.where( name: 'visit_site').first }

  it "changes event counter" do
    expect { Event.fire_event(event_type, @sponge,{}) }.to change { Event.count }
  end
end # with event_type is available create event

如果您试图使用
ActiveSupport::Testing::Assertions
模块中的
assert\u difference
Rspec
,则只需在
rails\u helper.rb
文件中插入以下代码即可

RSpec.describe "UsersSignups", type: :request do
  describe "signing up with invalid information" do
    it "should not work and should go back to the signup form" do
      get signup_path
      expect do
        post users_path, user: { 
          first_name:            "",
          last_name:             "miki",
          email:                 "user@triculi",
          password:              "buajaja",
          password_confirmation: "juababa" 
        }
      end.to_not change{ User.count }
      expect(response).to render_template(:new)
      expect(response.body).to include('errors')
    end
  end

  describe "signing up with valid information" do
    it "should work and should redirect to user's show view" do
      get signup_path
      expect do
        post_via_redirect users_path, user: { 
          first_name:            "Julito",
          last_name:             "Triculi",
          email:                 "triculito@mail.com",
          password:              "worldtriculi",
          password_confirmation: "worldtriculi"
        }
      end.to change{ User.count }.from(0).to(1)
      expect(response).to render_template(:show)
      expect(flash[:success]).to_not be(nil)
    end
  end
我已经用Rails 5.2.0对此进行了测试。但是,我想这应该行得通 还有其他版本

it 'event count should change' do
  assert_difference 'Event.count' do
    ...
  end
end

看起来你在用Rspec的assert_差异gem,对吗?我认为您需要将其包装在
it
块中。我尝试将其放置在block it中,但仍然存在此错误噢,在添加“config.include AssertDifference”spec\u helper.rb:43:in`block(2层)in:`uninitialized constant AssertDifference(namererror)到您的gem文件中添加了
gem'assert\u difference'吗?