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

时间:2012-03-15 02:42:54

标签: 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

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

4 个答案:

答案 0 :(得分:5)

如果您正在使用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

答案 1 :(得分:4)

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

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

将断言置于it块内:

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

答案 2 :(得分:4)

我最好使用change重写它。

这在RSpec 3.x中确实有效,但也可能在旧版本中使用。

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

答案 3 :(得分:0)

如果您尝试将A模块中的Bassert_difference一起使用,则只需在ActiveSupport::Testing::Assertions文件内插入以下代码即可。

Rspec
  

我已经用Rails 5.2.0对此进行了测试。但是,我认为这应该可行   以及其他版本。

相关问题