RSpec:未定义的方法`assert_difference'for ...(NoMethodError)

Pet*_*175 6 rspec rspec2 rspec-rails

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
Run Code Online (Sandbox Code Playgroud)

我搜索谷歌这个错误,但没有找到任何解决方法.请帮帮我.谢谢 :)

drj*_*nco 6

如果您正在使用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:                 "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
Run Code Online (Sandbox Code Playgroud)


Zek*_*ast 5

I'd better rewrite that using change.

That's work for sure in RSpec 3.x, but probably in older versions as well.

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
Run Code Online (Sandbox Code Playgroud)


Tom*_*m L 4

确保在spec/spec_helper.rb中包含AssertDifference:

RSpec.configure do |config|
  ...   
  config.include AssertDifference
end
Run Code Online (Sandbox Code Playgroud)

并将断言放入it块内:

it 'event count should change' do
  assert_difference 'Event.count' do
    ...
  end
end
Run Code Online (Sandbox Code Playgroud)