【问题标题】:Can rspec save data to database?rspec 可以将数据保存到数据库吗?
【发布时间】:2023-03-22 12:20:02
【问题描述】:

使用 httparty 通过 json 帖子创建用户会创建用户(如服务器日志所示),但测试在这两种情况下均失败。用户计数未更改或未找到用户。这是我对测试、规范或 rspec 处理创建数据库记录的方式的理解的问题吗?

结果:

  1) User signup and signin with native request with valid information should save the user
     Failure/Error: User.where(email: "bigbadwolf@example.com").should exist
       expected #<ActiveRecord::Relation []> to exist

  1) User signup and signin with native request with valid information should save the user
     Failure/Error: expect {
       result should have been changed by 1, but was changed by 0

规格:

describe "User", :type => :api do
  describe 'signup and signin' do 
  .
  .
   context "with native request" do
     context "with valid information" do
       it "should save the user" do 
        expect {
        response2 = HTTParty.post('http://localhost:3000/api/v1/registrations.json', 
        :body => { :user => 
          {
          :username => "bigbadwolf",
          :email => "bigbadwolf@example.com",
          :password => "mywolfie", 
          :password_confirmation => "mywolfie"
          } }.to_json,
       :headers => { 'Content-Type' => 'application/json', 'ClientType' => 'native', 'Accept' => 'application/json' })
       }.to change{User.count}.by(1) 
       User.where(email: "bigbadwolf@example.com").should exist
       .
       .
      end  
    end
    end
  end
end

日志:

(2.0ms)  BEGIN
  User Exists (1.0ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('bigbadwolf@example.com') LIMIT 1
  User Exists (1.0ms)  SELECT 1 AS one FROM "users" WHERE "users"."username" = 'bigbadwolf' LIMIT 1
  SQL (1.0ms)  INSERT INTO "users" ("created_at", "email", "password_digest", "updated_at", "username") VALUES ($1, $2, $3, $4, $5) RETURN
ING "id"  [["created_at", Tue, 25 Mar 2014 18:37:10 UTC +00:00], ["email", "bigbadwolf@example.com"], ["password_digest", "$2a$10$gGxQl6.W
O3.zb5EhPNL2A.m88vBIJ0DQ785PRjhxvorW4oDdYL4rC"], ["updated_at", Tue, 25 Mar 2014 18:37:10 UTC +00:00], ["username", "bigbadwolf"]]
   (1.0ms)  COMMIT
Completed 200 OK in 116ms (Views: 1.0ms | ActiveRecord: 11.0ms)

【问题讨论】:

  • 你能分享问题中失败的例子吗?
  • 您是否有理由不使用 post 能力中的工厂或 RSpecs 构建?你可以做post "/login", :username =&gt; "jdoe", :password =&gt; "secret"
  • 这会包括自定义标题吗?我正在使用 httparty,所​​以我可以添加自定义标头。

标签: ruby-on-rails json rspec


【解决方案1】:

Rspec 将数据保存到开发数据库而不是测试。我需要配置测试模式。

强制 rspec 使用测试数据库。

# spec_helper.rb
ENV["RAILS_ENV"] = 'test'

以测试模式运行服务器。

rails s -e test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2019-11-22
    • 2019-03-05
    • 2018-06-15
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多