2012-03-15 122 views
5
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的这个错误,但没有找到解决的办法。 请帮助我。谢谢:)RSpec:未定义的方法`assert_difference'for ...(NoMethodError)

+0

它看起来像你使用使用RSpec的一个assert_difference宝石,是否正确?我想你需要把它包装在一个'it'块中。 – 2012-03-15 03:53:13

+0

我试图把它放在块中,但仍然有这个错误 – 2012-03-15 06:54:59

回答

4

请务必包括AssertDifference在投机/ 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 
+1

哦,它添加“config.include AssertDifference” spec_helper.rb:43:在 ':未初始化的常量AssertDifference(NameError) – 2012-03-16 02:28:12

+1

您是否已将'gem'assert_difference''添加到您的Gemfile中? – 2012-03-16 11:08:01

+1

你说得对,我忘了:D – 2012-03-18 01:44:38

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 
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:     "[email protected]", 
      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 
相关问题