gpt4 book ai didi

ruby-on-rails-3 - 我将如何使用 Rspec 测试此 Controller 操作

转载 作者:行者123 更新时间:2023-11-28 20:46:34 26 4
gpt4 key购买 nike

我该如何规范

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

我目前的规范

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

规范结果

Failure/Error: response.response_code.should eq(200)

expected 200
got 422

(compared using ==)

路线

post 'like' => 'flags#like'

最佳答案

我将如何编写此测试:

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

希望这对您有所帮助。

关于ruby-on-rails-3 - 我将如何使用 Rspec 测试此 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com