RSpec: неопределенный метод `assert_difference' для (NoMethodError)

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

Я искал эту ошибку в Google, но ничего не нашел, чтобы ее исправить. Помоги мне, пожалуйста. Спасибо :)


person Peter89    schedule 15.03.2012    source источник
comment
Похоже, вы используете гем assert_difference с Rspec, верно? Я думаю, вам нужно обернуть его в блок it.   -  person Tom L    schedule 15.03.2012
comment
Я пытаюсь поместить его в блокировку, но все равно эта ошибка   -  person Peter89    schedule 15.03.2012


Ответы (4)


Убедитесь, что вы включили AssertDifference в spec/spec_helper.rb:

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

И поместите утверждение внутри блока it:

it 'event count should change' do
  assert_difference 'Event.count' do
    ...
  end
end
person Tom L    schedule 15.03.2012
comment
О, у него ошибка при добавлении config.include AssertDifference spec_helper.rb:43:in `блок (2 уровня) в ‹top (обязательно)›': неинициализированная константа AssertDifference (NameError) - person Peter89; 16.03.2012
comment
Вы добавили gem 'assert_difference' в свой Gemfile? - person Tom L; 16.03.2012

Если вы используете RSPEC, то, безусловно, нужно «изменить». Вот два примера, отрицательный и положительный, чтобы вы могли понять синтаксис:

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:                 "[email protected]",
          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
person drjorgepolanco    schedule 26.03.2015


Если вы пытаетесь использовать assert_difference из модуля ActiveSupport::Testing::Assertions с Rspec, все, что вам нужно сделать, это вставить приведенный ниже код в файл rails_helper.rb.

RSpec.configure do |config|
  config.include ActiveSupport::Testing::Assertions
end

Я тестировал это с Rails 5.2.0. Но я предполагаю, что это должно работать и с другими версиями.

person Abhilash Reddy    schedule 27.11.2019