我需要知道如何测试这个 Controller Action
def create_mobile
if mobile_user = MobileUser.authenticate(params[:email], params[:password])
session[:mobile_user_id] = mobile_user.id
respond_to do |format|
format.json { head :ok }
end
else
respond_to do |format|
format.json { head :unauthorised }
end
end
end
路由是对 session /create_mobile 的发布请求,如您所见,该操作仅响应 json
我当前的 Controller 规范如下所示
describe SessionsController, "Logging in" do
before(:each) do
@mobile_user = FactoryGirl.create(:valid_mobile_user)
end
it "Should log in mobile user" do
@request.env["HTTP_ACCEPT"] = "application/json"
post :create_mobile, {:password => @mobile_user.password, :email => @mobile_user.email}
response.should be_success
end
it "should fail log in mobile user" do
@request.env["HTTP_ACCEPT"] = "application/json"
post :create_mobile, {:password => 'joe', :email => @mobile_user.email}
response.should_not be_success
end
结束
测试结果在
1) SessionsController Logging in should log in mobile user
Failure/Error: response.should be_success
expected success? to return true, got false
# ./spec/controllers/sessions_controller_spec.rb:11:in `block (2 levels) in <top (required)>'
所以要么我的应用程序代码有问题,要么我的测试代码有问题,但无论哪种方式,验证方法都没有问题,因为 MobileUser 模型规范通过了,看起来像这样
it "should authenticate" do
mu = FactoryGirl.create(:valid_mobile_user)
assert_equal 1, MobileUser.count
assert_equal mu, MobileUser.authenticate(mu.email, mu.password)
end
非常感谢您对解决此问题的任何帮助。 提前致谢
更新 如下所示,使用
post :create_mobile, {:password => 'joe', :email => @mobile_user.email} :format => :json
或使用
@request.env["HTTP_ACCEPT"] = "application/json"
或两者结合没有区别
更新 2 测试刚刚开始工作,我无法理解(除了我从不明白为什么它一开始就不起作用)。 太奇怪了!
最佳答案
我最近遇到了同样的问题。下面是我的测试代码
post :create, :login => 'mock_user', :password => 'passwd', :format => :json
expected = {
:login => 'mock_user'
}.to_json
session[:user_id].should == mock_user.id
response.body.should == expected
测试结果为假,由response.body为空引起。我检查了 test.log,发现 Controller 中有 406 Not Acceptable 请求错误。在google了很多之后,我改为:format => 'json'。然后我得到了预期的测试结果。
关于ruby-on-rails - Rails 3.1 Rspec Rails 2 - 我如何测试这个 Controller Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8191616/