我在 rspec 中的 Controller 测试期间遇到问题。我创建了一个实体(存储在 postgres 中)并将 entity.id
作为 HTTP 请求
参数传递。我可以看到该实体已在测试中存储到数据库中,但 Controller 没有看到它。
所有数据库请求都发生在一个事务中,所以我认为这会是问题所在。
我有很多类似的测试,所以数据库连接和类似的东西都没有问题。
我尝试将 create :entity
移动到 before block ,并将其作为 Entity.all.first.id
加载到请求中。
使用 let!(:entity) {create :entity}
也没有用。也从上下文中取出它。
// notifications_controller_spec.rb
context 'with an entity' do
it 'renders the list of notifications' do
entity = create :entity
pp Entity.all // returns array with stored entity
get :index, entity: entity.id
expect(response.status).to eq 200
expect(response).to render_template 'index'
end
end
//notifications_controller.rb
def index
pp Entity.all // returns empty array
defaults_entity
return render 'welcome_no_entity' if @entity.nil?
@notifications = NotificationDecorator.decorate_collection(
Notification::EntityScopedQuery.
new(@entity.id, { order: { created_at: :desc } }).
all
)
end
我希望看到存储的是与测试中相同的实体。
可能会有一些愚蠢的错误。感谢您的帮助。
编辑1:
// create entity
INSERT INTO "entities" ("name", "type", "customer_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["name", "test"], ["type", "complex"], ["customer_id", 514911], ["created_at", "2019-01-24 08:43:00.145471"], ["updated_at", "2019-01-24 08:43:00.145471"]]
// select in test
SELECT "entities".* FROM "entities"
没有像 SELECT "entities".* FROM "entities"
这样的日志,即使应该有。我也可以说,select 是从测试中来的。
最佳答案
问题是,我们在 Controller 中使用了 gem Multitenant
。所以在 Controller 中,它不会像 SELECT * FROM entities WHERE id = ?
这样选择,而是 SELECT "entities".* FROM "entities"WHERE "entities"."customer_id"= $1
customer_id
没有定义,所以它完全是随机的。
在测试中修复:entity = create :entity, customer_id: customer_id
关于ruby-on-rails - 为什么在 rspec 测试中创建并存储在数据库中的项目,但应用程序看不到它存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54342335/