我的before_action
中有一个application_controller
,它使用令牌来授权API访问。
before_action :authenticate
def authenticate
User.find_by_auth_token(params[:token]) || render_unauthorized
end
如何将它放入我的测试中?
teams_controller_spec:
let(:valid_attributes) { { :name => 'Test', :year => 2014 } }
describe "GET index" do
it "assigns all teams as @teams" do
team = Team.create! valid_attributes
get :index, {}, valid_session
assigns(:teams).should eq([team])
end
end
当我运行测试时出现错误:
expected: #<Team id: 1, name: "Test", year: 2014, created_at: "2014-08-13 12:07:49", updated_at: "2014-08-13 12:07:49">
got: nil
如果我删除了验证测试通行证。
答案 0 :(得分:2)
您正在使用params [:token]
验证请求解决问题的一种方法是在运行test
之前使用FactoryGirl创建具有auth令牌的有效用户示例:
before(:each) do
@user = FactoryGirl.create(:user)
end
在编写测试时,传递用户令牌
describe "GET index" do
it "assigns all teams as @teams" do
team = Team.create! valid_attributes
get :index, {token: @user.auth_token}, valid_session
assigns(:teams).should eq([team])
end
end