RSpec不会删除DB记录,因此第二次运行时它会失败

时间:2011-06-07 02:43:03

标签: ruby-on-rails rspec

这是Michael Hartl的书第8.4节。 RSpec正在测试成功注册,但由于电子邮件地址不是唯一的,因此失败。因此,如果我进入代码并更新规范中的电子邮件地址,它将在我第一次运行时运行,但不是第二次运行。我已经确认了这一点,因为我可以通过更改电子邮件地址或以其他方式运行rake db:test:clone来进行测试。

如何克服这一点的任何想法将不胜感激。

代码:     需要'spec_helper'

describe "Users" do
  describe "signup" do
    describe "failure" do
      it "should not make a new user" do
        lambda do
          visit signup_path
          fill_in :user_name,               :with => "" #you can use CSS id instead of label, which is probably better
          fill_in "Email",                  :with => ""
          fill_in "Password",               :with => ""
          fill_in "Password confirmation",  :with => ""
          click_button
          response.should render_template('users/new')
          response.should have_selector("div#error_explanation")
        end.should_not change(User, :count)
      end
    end
    describe "success" do
      it "should make a new user" do
        lambda do
          visit signup_path
          fill_in "Name",                   :with => "Example User"
          fill_in "Email",                  :with => "alex@example.com"
          fill_in "Password",               :with => "foobar"
          fill_in "Password confirmation",  :with => "foobar"
          click_button
          response.should have_selector("div.flash.success", :content => "Welcome")
          response.should render_template('users/show')
        end.should change(User, :count).by(1)
      end
    end 
  end
end

1 个答案:

答案 0 :(得分:5)

spec / spec_helper.rb文件是什么样的?你有交易吗?

RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

这会在数据库事务中运行每个规范,并在每次测试运行后将其恢复为原始状态。

一旦你的规范助手看起来像这样,运行:

rake db:test:prepare

再试一次。如果这不起作用,您能提供更多信息吗?哪个版本的RSpec?哪个版本的Rails?