我正在使用'Api'命名空间,我想为我的控制器编写测试。但是,我无法让post方法为此工作。
我试过
describe Api::EnvsController do
describe "POST create" do
it "creates a new env" do
expect { post :create, :env => { :name => "This_te" } }.to change(Env,:count).by(1)
end
end
end
describe EnvsController do
describe "POST create" do
it "creates a new env" do
expect { post :create, :env => {:name => "mym"} }.to change(Env,:count).by(1)
end
end
end
错误:
4) Api::EnvsController POST create creates a new env
Failure/Error: expect { post :create, :env => {:name => "mym"} }.to change(Env,:count).by(1)
ActionController::UnknownFormat:
ActionController::UnknownFormat
# ./app/controllers/api/envs_controller.rb:5:in `create'
# ./spec/controllers/api/envs_controller_spec.rb:7:in `block (4 levels) in <top (required)>'
# ./spec/controllers/api/envs_controller_spec.rb:7:in `block (3 levels) in <top (required)>'
5) EnvsController POST create creates a new env
Failure/Error: expect { post :create, :env => {:name => "mym"} }.to change(Env,:count).by(1)
ActionController::UrlGenerationError:
No route matches {:env=>{:name=>"mym"}, :controller=>"envs", :action=>"create"}
# ./spec/controllers/envs_controller_spec.rb:7:in `block (4 levels) in <top (required)>'
# ./spec/controllers/envs_controller_spec.rb:7:in `block (3 levels) in <top (required)>'
这让我相信'post:create,:env =&gt; :name =&gt; “string”} ......'工作不正常。虽然我已经尝试了基于RSpec的post方法的所有推导,但是这里有样本。
post "/widgets", :widget => {:name => "My Widget"}
当我改变它以满足我的需要时
expect { post "api/envs", :env => { :name => "This_te" } }.to change(Env,:count).by(1)
我收到一个url生成错误,说我没有匹配它的路由。 IE
5) Api::EnvsController POST create creates a new env
Failure/Error: expect { post "/api/envs", :env => { :name => "This_te" } }.to change(Env,:count).by(1)
ActionController::UrlGenerationError:
No route matches {:env=>{:name=>"This_te"}, :controller=>"api/envs", :action=>"/api/envs"}
# ./spec/controllers/api/envs_controller_spec.rb:7:in `block (4 levels) in <top (required)>'
# ./spec/controllers/api/envs_controller_spec.rb:7:in `block (3 levels) in <top (required)>'
根据要求从控制器创建。
def create
@env = Env.new(env_params)
respond_to do |format|
if @env.save
format.json { render json: @env, status: :created }
else
format.json { render json: @env.errors, status: :unprocessable_entity }
end
end
end