【发布时间】:2018-06-20 11:49:22
【问题描述】:
我是 Rails 测试新手,我想测试我的 Rails 控制器 API。 我在我的 Gemfile 中像这样使用 gems rails-rspec 、capybara 和 database-cleaner:
group :development, :test do
gem 'rspec-rails', '~> 3.7'
end
group :test do
gem 'database_cleaner'
gem 'capybara'
end
在我的规范文件夹中,我创建了一个控制器并在我的 api 文件夹中创建了一个 user_controller_spec.rb 并想要测试创建一个具有有效参数的用户并编写如下代码:
RSpec.describe "API V1 Users", type: 'request' do
describe "POST /api/v1/users" do
context "with valid parameters" do
let(:valid_params) do
{
fname: "Riya",
lname: "******",
email: "*******.com",
password: "",
contact: "2144333",
country_code:"91",
address: "Sector 63",
city: "Noida",
state: "UP",
country: "India",
zipcode: "23001",
role: "***",
image: ""
}
end
it "creates a new user" do
expect { post "/api/v1/users", params: valid_params}
expect(response).to have_http_status(:ok) # it's use for code 200
end
it "creates a user with the correct attributes" do
post "/api/v1/users", params: valid_params
expect(User.last).to have_attributes valid_params
end
end
context "with invalid parameters" do
# testing for validation failures is just as important!
# ...
end
end
end
但它给了我错误:
Failure/Error: expect(User.last).to have_attributes valid_params expected nil to respond to :fname, :lname, :email, :password, :contact
【问题讨论】:
-
请显示控制器操作和模型验证
-
看起来您的参数无效并且用户未保存到数据库中
-
post "/api/v1/users", params: valid_params您的帖子操作不会创建用户,这会导致 User.last 成为nil调试您的控制器操作。 -
它创建一个用户并返回一个 id 为 1 的用户但是当我检查我的数据库时我没有看到该用户并且错误是 Error: expect(User.last).to have_attributes valid_params
-
预期 # 具有属性 {:email => "xxx@xxx.com", :password => "123456", :fname => "Riya", :lname => "", :角色 => "", :...地址 => "xx", :city => "xx", :state => "x", :country => "x", :zipcode => "x", : image => ""} 但有属性 {:email => "xxx@xxx.com", :password => nil, :fname => "Riya", :lname => "Rajput", :role => "business ", :conta...dress => "Sector 63", :city => "Noida", :state => "UP", :country => "India", :zipcode => "23", :image = > 无}
标签: ruby-on-rails ruby testing rspec-rails