首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 3+ PostgreSQL + RSpec: App运行良好,但RSpec示例失败

Rails 3+ PostgreSQL + RSpec: App运行良好,但RSpec示例失败
EN

Stack Overflow用户
提问于 2012-07-29 14:26:39
回答 1查看 1K关注 0票数 1

我正在使用gem作为中间件开发Rails 3.2应用程序。应用程序本身工作得很好,所有的RSpec示例在单独运行时也都运行得很好。但是,当我使用bundle exec rspec命令同时运行所有测试时,有两个示例在两个不同的控制器规范中失败,它们所做的事情完全相同。以下是两个有问题的例子:

issues_controller_spec.rb文件中:

代码语言:javascript
复制
describe "GET 'new'" do

  # ...

  context "for authenticated users" do
    before(:each) do
      controller.log_in(create(:user))
      get :new
    end

    # ...

    it "should create a new issue instance and put it in an instance variable" do
      assigns(:issue).should be_an_instance_of Issue
    end
  end
end

users_controller_spec.rb文件中:

代码语言:javascript
复制
describe "GET 'new'" do

    # ...

  context "for authenticated users" do

      # ...

    context "for admin users" do
      before(:each) do
        admin = create(:admin)
        admin.add_role :admin
        controller.log_in(admin)
        get :new
      end

      # ...

      it "should create a new User instance and put it in an instance variable" do
        assigns(:user).should be_an_instance_of User
      end
    end
  end
end

这两个示例受预挂钩的影响:

代码语言:javascript
复制
before(:each) do
  client = create(:client)
  @request.host = "#{client.account_name}.lvh.me"
end

在创建新客户端时,有一个after_create回调:

代码语言:javascript
复制
# Create the client database (Apartment) for multi-tenancy
def create_client_database
  begin
    Apartment::Database.create(self.account_name)
  rescue Apartment::SchemaExists
    return
  rescue
    self.destroy
  end
end

这些例子都失败了。现在,如果删除begin...rescue...end块并保留行Apartment::Database.create(self.account_name),那么在下面的示例中将得到以下异常:

代码语言:javascript
复制
ActiveRecord::StatementInvalid:
   PG::Error: ERROR:  current transaction is aborted, commands ignored until end of transaction block
   : SET search_path TO public

同样,如果我单独运行示例,它们会传递,但是如果我运行所有示例,上面的两个示例将失败。

有人知道我做错了什么吗?

注意事项:整个应用程序代码都可以找到这里

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-30 23:11:38

我通过将行client = create(:client)封装在一个beginrescueend块中解决了这个问题,如下所示:

代码语言:javascript
复制
before(:each) do
  begin
    client = create(:client)
  rescue
    client = Client.create!(attributes_for(:client))
  end

  @request.host = "#{client.account_name}.lvh.me"
end

我不知道它是怎么工作的,也不知道为什么,但我知道它是有效的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11709997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档