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

1 rspec ruby-on-rails

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

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

代码:require'pec_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
Run Code Online (Sandbox Code Playgroud)

Dan*_*oak 5

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

RSpec.configure do |config|
  config.use_transactional_fixtures = true
end
Run Code Online (Sandbox Code Playgroud)

这将在数​​据库事务中运行每个规范,并在每次测试运行后将其返回到其原始状态.

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

rake db:test:prepare
Run Code Online (Sandbox Code Playgroud)

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