我正在使用Apartment gem作为中间件开发此Rails 3.2应用程序。应用程序本身运行良好,所有RSpec示例在单独运行时也能完美运行。但是,当我使用bundle exec rspec
命令同时运行所有测试时,有两个示例在两个不同的控制器规范中失败,并且它们执行完全相同的操作。以下是两个问题的例子:
在issues_controller_spec.rb
文件中:
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
文件中:
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
这两个例子受到前钩子的影响:
before(:each) do
client = create(:client)
@request.host = "#{client.account_name}.lvh.me"
end
创建新客户端时,会有after_create
回调:
# 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)
,我会在令人心烦的示例中得到以下异常:
ActiveRecord::StatementInvalid:
PG::Error: ERROR: current transaction is aborted, commands ignored until end of transaction block
: SET search_path TO public
同样,如果我单独运行这些示例,它们会通过,但如果我运行所有示例,则上面的两个示例都会失败。
有人知道我做错了吗?
注意:可以找到整个应用程序代码here。
答案 0 :(得分:0)
我通过将行client = create(:client)
包裹在begin
,rescue
,end
块中来解决此问题,如下所示:
before(:each) do
begin
client = create(:client)
rescue
client = Client.create!(attributes_for(:client))
end
@request.host = "#{client.account_name}.lvh.me"
end
我不知道这是如何或为何有效,但我知道它有效。