RSPEC be_valid不一致

时间:2013-06-12 23:06:04

标签: ruby-on-rails rspec factory-bot spork

我的大多数测试都在工作,但出于某种原因,FactoryGirl.build ... should_not be_valid在此声明的末尾不起作用

describe "exceed the maximum number of subscriptions" do 
  @user = FactoryGirl.create(:user)
  loop_count = GlobalVar::MAX_SUBSCRIPTIONS
  loop_count.times do 
    @topic = FactoryGirl.create(:topic)
    @subscription = FactoryGirl.create(:subscription, topic: @topic, user: @user)
  end
  @topic = FactoryGirl.create(:topic)
  FactoryGirl.build(:subscription, topic: @topic, user: @user).should_not be_valid
end

在同一规范中,这成功通过:

it "has a maximum length bio" do 
    FactoryGirl.build(:user, bio: "a"*251).should_not be_valid
end

这是我得到的错误的开始:

(druby://192.168.1.118:53053) C:/Sites/mavens/spec/models/user_spec.rb:42:in `block (3 levels) in <top (required)>': undefined local variable or method `be_valid' for #<Class:0x7e49290> (NameError)
    from (druby://192.168.1.118:53053) C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/rspec-core-2.11.1/lib/rspec/core/example_group.rb:238:in `module_eval'

我正在使用Spork和Guard进行测试。我为每次运行在spec_helper中重新加载了FactoryGirl。已经多次重新启动spork并且它在重启时不起作用。如果我的任何其他代码都有帮助,请告诉我,并且一如既往地感谢您的帮助!!

1 个答案:

答案 0 :(得分:1)

您需要在it块内放置测试:

describe "exceed the maximum number of subscriptions" do 
  it do
    user = FactoryGirl.build(:user)
    GlobalVar::MAX_SUBSCRIPTIONS.times do
      topic = FactoryGirl.build(:topic)
      FactoryGirl.build(:subscription, topic: topic, user: user)
    end
    topic = FactoryGirl.build(:topic)
    FactoryGirl.build(:subscription, topic: topic, user: user).should_not be_valid
  end
end

这是由于RSpec如何处理DSL的上下文。