我刚刚为我的模型添加了一个新函数,并希望使用rspec进行测试。看起来好像我做错了,因为我的测试一直在失败并且数据库中没有存储任何东西。我想要的是让用户阻止另一个用户。
我的用户模型包含以下内容:
has_many :blockeds
has_many :blocked_users, :through=> :blockeds
我的user_controller有以下内容:
def block
block_action = Blocked.new
block_action.add_blocked(current_user.id,params[:id])
current_user.blockeds << User.find(params[:id])
end
def is_blocked
blocked = current_user.blocked_by(current_user.id,params[:id])
blocked
end
我的Blocked模型有以下内容:
belongs_to :user_blocking, class_name: 'User'
belongs_to :user_blocked, class_name: 'User'
def add_blocked(blocking_id,blocked_id)
self.user_blocking_id = blocking_id
self.user_blocked_id = blocked_id
self.save!
end
这是我的测试:
describe 'Block' do
let(:user_one) { Fabricate :user }
let(:user_two) { Fabricate :user }
it 'should block a user' do
post :block, current_user: user_one.to_param, id: user_two.id.to_param, format: :json
expect{
post :is_blocked, current_user: user_one.to_param, id: user_two.id.to_param, format: :json
}.to eq(user_two)
end
end
我想测试user_two是否被user_one阻止了。没有任何东西存储在数据库中。有什么帮助吗?
这是我在完成测试后得到的结果:
expected: #<User id: 2, email: "arden@hotmail.com", encrypted_password: "$2a$04$cKnZx8h9nVX1xQOruH6.yeSHIl989EA.amK.fqz4kwz...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2014-12-23 13:48:32", updated_at: "2014-12-23 13:48:32", bio: nil, fb_access_token: "accusamuscumsit", fb_app_id: "essesedmaiores", phone: nil, address: nil, authentication_token: "vH3N1KTz1AVmP8fTRAye", gender: "male", profile_completed: false, zip_code: "95304-2111", state: "Indiana", city: "New Chaunceymouth", latitude: 37.6841772, longitude: -121.3770336, access_code_id: nil, locked_at: nil, cover: nil, fb_global_id: nil, birthday: "1996-02-18", age: 226, channel_id: "mh3_dPdbihISTdX8TCOKkQ", first_name: "Tressa", last_name: "Keeling", access_code_type: nil, facebook_data_updated_at: nil>
got: #<Proc:0x00000107fafd68@/Users/toptierlabs/Documents/projects/kinnecting_backend/spec/controllers/api/users_controller_spec.rb:206>
答案 0 :(得分:0)
您正在将一个块传递给expect
,该版本旨在用于您想要评估该块的执行如何改变环境的情况(例如,通过to_change
)。它通常在交易环境中执行,但在您的情况下,由于您只是将其与eq
匹配器一起使用,因此它根本没有被执行。
如果要检查控制器操作返回的值,则需要检查response
的值,如下所示:
post :is_blocked, current_user: user_one.to_param, id: user_two.id.to_param, format: :json
expect(response.body).to eq(user_two.to_json)