无法通过Post在Rspec中创建模型
我正在尝试在Rspec中创建一个用户:
require "rails_helper" RSpec.describe UsersController, type: :controller do describe "POST #index" do it 'should create a user' do post :create, {name: "name1", age: 25}.to_json, format: :json # .............
但我每次都会收到validation错误: name can't be blank, age can't be blank
UserController接受json:
def create @user = User.new(params1) if @user.save render json: @user else render json: @user.errors, status: :unprocessable_entity end end def params1 params.permit(:id, :name, :age) end
发送给create
的参数不应该是json String而是Hash。
从rspec文档 :
require "rails_helper" RSpec.describe WidgetsController, :type => :controller do describe "responds to" do it "responds to custom formats when provided in the params" do post :create, { :widget => { :name => "Any Name" }, :format => :json } expect(response.content_type).to eq "application/json" end end end
所以你的测试应该是:
require "rails_helper" RSpec.describe UsersController, type: :controller do describe "POST #create" do it 'should create a user' do post :create, { user: {name: "name1", age: 25}, :format => :json } ...
- FactoryGirl未注册(只有一家工厂遇到此事)
- 为什么我得到FactoryGirl错误的参数数量错误?
- Factory Girl + Rspec给出以下错误:ActionView :: Template :: Error :(对象id)不是id值
- 使用RSpec 3和Rails 4在控制器测试中查找新创建的记录
- rspec –init not working /`mkd ir’:参数无效 – ./C :( Errno :: EINVAL)
- WebMock:Rspec – 使用JSON响应测试Facebookvalidation
- Rails模型测试 – 模拟与工厂
- Paperclip + RSpec:content_typevalidation
- ActionDispatch :: Http :: UploadedFile.content_type未在Rspec测试中初始化