How should I spec this
class FlagsController
def like
flag = current_user.flags.find_or_initialize_by_flaggable_type_and_flaggable_id(params[:like_type], params[:like_id])
flag.kind = params[:kind]
if flag.save
head :ok
else
head :unprocessable_entity
end
end
end
My current spec
describe FlagsController do
before (:each) do
@user = Factory(:user)
sign_in @user
end
describe "flag" do
it 'with valid params' do
controller.stub!(:current_user).and_return(@user)
@user.stub_chain(:flags, :find_or_initialize_by_flaggable_type_and_flaggable_id).
with('Comment', '1').
and_return(mock_flag(:save => false)).
stub!(:kind).
with('up').
and_return(mock_flag(:save => true))
post :like, :like_type => 'Comment', :like_id => '1', :kind => 'up'
response.response_code.should eq(200)
end
end
Spec results
Failure/Error: response.response_code.should eq(200)
expected 200
开发者_Python百科 got 422
(compared using ==)
Route
post 'like' => 'flags#like'
How I would write this test:
describe FlagsController do
before (:each) do
@user = Factory(:user)
sign_in @user
end
describe "post :like" do
before(:each) do
controller.stub!(:current_user).and_return(@user)
@mock_flag = mock(Flag)
@mock_flag.should_receive(:kind=).with('up')
@user.stub_chain(:flags, :find_or_initialize_by_flaggable_type_and_flaggable_id).
with('Comment', '1').and_return(@mock_flag)
end
context 'when save fails' do
before(:each) do
@mock_flag.should_receive(:save).and_return(false)
post :like, :like_type => 'Comment', :like_id => '1', :kind => 'up'
end
it { response.should be_unprocessable_entity }
end
context 'when save succeeds' do
before(:each) do
@mock_flag.should_receive(:save).and_return(true)
post :like, :like_type => 'Comment', :like_id => '1', :kind => 'up'
end
it { response.status.should be == 200 }
end
end
Hope this helps.
精彩评论