使用httparty通过json帖子创建用户创建用户(如服务器日志所示),但测试在两个条件下都失败。用户计数未更改或未找到用户。这是我对测试,规范或rspec处理创建db记录的方式的理解的问题吗?
结果:
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)
答案 0 :(得分:1)
Rspec将数据保存到开发数据库而不是测试。我需要配置测试模式。
强制rspec使用测试数据库。
# spec_helper.rb
ENV["RAILS_ENV"] = 'test'
以测试模式运行服务器。
rails s -e test