简体   繁体   English

Rails 4:如何测试控制器动作

[英]Rails 4: How to test Controller Action

How do I actually test this Controller Action, I wrote in my PurchasesController: 我在PurchasesController中写道,我如何实际测试此Controller Action:

protect_from_forgery except: [:hook]
def hook
    params.permit! # Permit all Paypal input params
    status = params[:payment_status]
    if status == "Completed"
        @purchase = Purchase.find(params[:invoice])
        @purchase.update_attributes(status: status, transaction_id: params[:txn_id], purchased_at: Time.now)
        @purchase.save!
        @user = @tool.user
        @user.earned_money += @tool.price
        @user.save!
    end
    render nothing: true
end

preferably with my Rails Console? 最好使用我的Rails Console?

Routes: 路线:

post "/purchases/:id" => "purchases#show"
post "/hook" => "purchases#hook"

You don't test controllers through the rails console. 您不会通过Rails控制台测试控制器。

Controllers in Rails respond to HTTP requests - they are instantiated by the routing component when it matches an incoming request. Rails中的控制器响应HTTP请求-当路由组件与传入请求匹配时,它们将由路由组件实例化。 So you would test controllers by sending a HTTP request and inspecting the response. 因此,您可以通过发送HTTP请求并检查响应来测试控制器。

You can manually test your controller by using the command line tool cURL or the browser based Postman to send a request*. 您可以使用命令行工具cURL或基于浏览器的Postman发送请求*,以手动测试控制器。 You can the use the rails console to check for side effects such as changes in the database. 您可以使用rails控制台检查副作用,例如数据库中的更改。

However, you should consider using an automated testing tool such as Minitest or RSpec as manually testing your application is a flawed approach. 但是,您应该考虑使用自动测试工具(例如MinitestRSpec),因为手动测试应用程序是一种有缺陷的方法。

I'm not totally sure you can test this through your console, unless you decouple/abstract the other operations being performed and then you test the units independently. 我不确定您是否可以通过控制台进行测试,除非您解耦/抽象了正在执行的其他操作,然后分别测试了单元。 With RSpec/Minitest, though you just have to create the records and do a post request to the /hook route, passing the expected params: invoice , txn_id , payment_status . 使用RSpec / Minitest,尽管您只需要创建记录并向/hook路由发出发布请求,并传递预期的参数: invoicetxn_idpayment_status

Let me know if that helps. 让我知道是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM