|
1 | 1 | require 'spec_helper' |
2 | 2 |
|
3 | 3 | describe UsersController, type: :controller do |
| 4 | + include_context 'JSON API headers' |
| 5 | + |
4 | 6 | before(:all) { FactoryGirl.create_list(:user, 3, :with_posts) } |
5 | 7 |
|
6 | 8 | let(:fields) { (UserResource.fetchable_fields - %i(id posts)).map(&:to_s) } |
7 | 9 | let(:relationships) { %w(posts) } |
| 10 | + let(:attributes) { { first_name: 'Yehuda', last_name: 'Katz' } } |
| 11 | + |
| 12 | + let(:user_params) do |
| 13 | + { data: { type: 'users', attributes: attributes } } |
| 14 | + end |
8 | 15 |
|
9 | 16 | include_examples 'JSON API invalid request', resource: :users |
10 | 17 |
|
|
225 | 232 | end |
226 | 233 | end |
227 | 234 | end |
| 235 | + |
| 236 | + describe '#create' do |
| 237 | + it 'creates a new user' do |
| 238 | + expect { post :create, user_params }.to change(User, :count).by(1) |
| 239 | + expect(response).to have_http_status :created |
| 240 | + expect(response).to have_primary_data('users') |
| 241 | + expect(response).to have_data_attributes(fields) |
| 242 | + expect(data['attributes']['first_name']).to eq(user_params[:data][:attributes][:first_name]) |
| 243 | + end |
| 244 | + |
| 245 | + shared_examples_for '400 response' do |hash| |
| 246 | + it 'renders a 400 response' do |
| 247 | + user_params[:data][:attributes].merge!(hash) |
| 248 | + expect { post :create, user_params }.to change(User, :count).by(0) |
| 249 | + expect(response).to have_http_status :bad_request |
| 250 | + expect(error['title']).to eq('Param not allowed') |
| 251 | + expect(error['code']).to eq(105) |
| 252 | + end |
| 253 | + end |
| 254 | + |
| 255 | + context 'with a not permitted param' do |
| 256 | + it_behaves_like '400 response', foo: 'bar' |
| 257 | + end |
| 258 | + |
| 259 | + context 'with a param not present in resource\'s attribute list' do |
| 260 | + it_behaves_like '400 response', admin: true |
| 261 | + end |
| 262 | + |
| 263 | + context 'when validation fails' do |
| 264 | + it 'render a 422 response' do |
| 265 | + user_params[:data][:attributes].merge!(first_name: nil) |
| 266 | + expect { post :create, user_params }.to change(User, :count).by(0) |
| 267 | + expect(response).to have_http_status :unprocessable_entity |
| 268 | + expect(error['title']).to eq('Can\'t change this User') |
| 269 | + expect(error['code']).to eq(125) |
| 270 | + end |
| 271 | + end |
| 272 | + end |
228 | 273 | end |
0 commit comments