jam*_*esc 3 json ruby-on-rails rspec-rails
我需要知道如何测试这个控制器动作
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
Run Code Online (Sandbox Code Playgroud)
该路由是对sessions/create_mobile的发布请求,您可以看到该操作仅响应json
我当前的控制器规格看起来像这样
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
Run Code Online (Sandbox Code Playgroud)
结束
测试结果如下
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)>'
Run Code Online (Sandbox Code Playgroud)
所以我的应用程序代码有问题或我的测试代码出现问题,但无论哪种方式,authenticate方法都没有问题,因为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
Run Code Online (Sandbox Code Playgroud)
任何帮助整理这一点非常感谢.提前致谢
更新 如下所述,使用
post :create_mobile, {:password => 'joe', :email => @mobile_user.email} :format => :json
或使用
@request.env["HTTP_ACCEPT"] = "application/json"
Run Code Online (Sandbox Code Playgroud)
或两者的结合没有区别
更新2 测试刚刚开始工作,我无法理解(除了我从来没有理解为什么它不起作用).完全奇怪!
小智 9
我最近遇到了同样的问题.下面是我的测试代码
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
Run Code Online (Sandbox Code Playgroud)
测试结果为false,由response.body为空.我检查了test.log,发现控制器中出现406不可接受的请求错误.经过google搜索后,我改为:format =>'json'.然后我得到了预期的测试结果.
| 归档时间: |
|
| 查看次数: |
2764 次 |
| 最近记录: |